babylon.no-module.max.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. /** @hidden */
  414. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  415. // Rebuild shaders source code
  416. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  417. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  418. vertexCode = prefix + vertexCode;
  419. fragmentCode = prefix + fragmentCode;
  420. // Number lines of shaders source code
  421. var i = 2;
  422. var regex = /\n/gm;
  423. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  424. i = 2;
  425. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  426. // Dump shaders name and formatted source code
  427. if (this.name.vertexElement) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  430. }
  431. else if (this.name.vertex) {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  434. }
  435. else {
  436. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  437. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  438. }
  439. };
  440. ;
  441. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  442. var preparedSourceCode = this._processPrecision(sourceCode);
  443. if (this._engine.webGLVersion == 1) {
  444. callback(preparedSourceCode);
  445. return;
  446. }
  447. // Already converted
  448. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  449. callback(preparedSourceCode.replace("#version 300 es", ""));
  450. return;
  451. }
  452. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  453. // Remove extensions
  454. // #extension GL_OES_standard_derivatives : enable
  455. // #extension GL_EXT_shader_texture_lod : enable
  456. // #extension GL_EXT_frag_depth : enable
  457. // #extension GL_EXT_draw_buffers : require
  458. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  459. var result = preparedSourceCode.replace(regex, "");
  460. // Migrate to GLSL v300
  461. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  462. result = result.replace(/attribute[ \t]/g, "in ");
  463. result = result.replace(/[ \t]attribute/g, " in");
  464. if (isFragment) {
  465. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  467. result = result.replace(/texture2D\s*\(/g, "texture(");
  468. result = result.replace(/textureCube\s*\(/g, "texture(");
  469. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  470. result = result.replace(/gl_FragColor/g, "glFragColor");
  471. result = result.replace(/gl_FragData/g, "glFragData");
  472. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  473. }
  474. callback(result);
  475. };
  476. Effect.prototype._processIncludes = function (sourceCode, callback) {
  477. var _this = this;
  478. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  479. var match = regex.exec(sourceCode);
  480. var returnValue = new String(sourceCode);
  481. while (match != null) {
  482. var includeFile = match[1];
  483. // Uniform declaration
  484. if (includeFile.indexOf("__decl__") !== -1) {
  485. includeFile = includeFile.replace(/__decl__/, "");
  486. if (this._engine.supportsUniformBuffers) {
  487. includeFile = includeFile.replace(/Vertex/, "Ubo");
  488. includeFile = includeFile.replace(/Fragment/, "Ubo");
  489. }
  490. includeFile = includeFile + "Declaration";
  491. }
  492. if (Effect.IncludesShadersStore[includeFile]) {
  493. // Substitution
  494. var includeContent = Effect.IncludesShadersStore[includeFile];
  495. if (match[2]) {
  496. var splits = match[3].split(",");
  497. for (var index = 0; index < splits.length; index += 2) {
  498. var source = new RegExp(splits[index], "g");
  499. var dest = splits[index + 1];
  500. includeContent = includeContent.replace(source, dest);
  501. }
  502. }
  503. if (match[4]) {
  504. var indexString = match[5];
  505. if (indexString.indexOf("..") !== -1) {
  506. var indexSplits = indexString.split("..");
  507. var minIndex = parseInt(indexSplits[0]);
  508. var maxIndex = parseInt(indexSplits[1]);
  509. var sourceIncludeContent = includeContent.slice(0);
  510. includeContent = "";
  511. if (isNaN(maxIndex)) {
  512. maxIndex = this._indexParameters[indexSplits[1]];
  513. }
  514. for (var i = minIndex; i < maxIndex; i++) {
  515. if (!this._engine.supportsUniformBuffers) {
  516. // Ubo replacement
  517. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  518. return p1 + "{X}";
  519. });
  520. }
  521. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  522. }
  523. }
  524. else {
  525. if (!this._engine.supportsUniformBuffers) {
  526. // Ubo replacement
  527. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  528. return p1 + "{X}";
  529. });
  530. }
  531. includeContent = includeContent.replace(/\{X\}/g, indexString);
  532. }
  533. }
  534. // Replace
  535. returnValue = returnValue.replace(match[0], includeContent);
  536. }
  537. else {
  538. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  539. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  540. Effect.IncludesShadersStore[includeFile] = fileContent;
  541. _this._processIncludes(returnValue, callback);
  542. });
  543. return;
  544. }
  545. match = regex.exec(sourceCode);
  546. }
  547. callback(returnValue);
  548. };
  549. Effect.prototype._processPrecision = function (source) {
  550. if (source.indexOf("precision highp float") === -1) {
  551. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  552. source = "precision mediump float;\n" + source;
  553. }
  554. else {
  555. source = "precision highp float;\n" + source;
  556. }
  557. }
  558. else {
  559. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  560. source = source.replace("precision highp float", "precision mediump float");
  561. }
  562. }
  563. return source;
  564. };
  565. /**
  566. * Recompiles the webGL program
  567. * @param vertexSourceCode The source code for the vertex shader.
  568. * @param fragmentSourceCode The source code for the fragment shader.
  569. * @param onCompiled Callback called when completed.
  570. * @param onError Callback called on error.
  571. */
  572. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  573. var _this = this;
  574. this._isReady = false;
  575. this._vertexSourceCodeOverride = vertexSourceCode;
  576. this._fragmentSourceCodeOverride = fragmentSourceCode;
  577. this.onError = function (effect, error) {
  578. if (onError) {
  579. onError(error);
  580. }
  581. };
  582. this.onCompiled = function () {
  583. var scenes = _this.getEngine().scenes;
  584. for (var i = 0; i < scenes.length; i++) {
  585. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  586. }
  587. if (onCompiled) {
  588. onCompiled(_this._program);
  589. }
  590. };
  591. this._fallbacks = null;
  592. this._prepareEffect();
  593. };
  594. /**
  595. * Gets the uniform locations of the the specified variable names
  596. * @param names THe names of the variables to lookup.
  597. * @returns Array of locations in the same order as variable names.
  598. */
  599. Effect.prototype.getSpecificUniformLocations = function (names) {
  600. var engine = this._engine;
  601. return engine.getUniforms(this._program, names);
  602. };
  603. /**
  604. * Prepares the effect
  605. */
  606. Effect.prototype._prepareEffect = function () {
  607. var attributesNames = this._attributesNames;
  608. var defines = this.defines;
  609. var fallbacks = this._fallbacks;
  610. this._valueCache = {};
  611. var previousProgram = this._program;
  612. try {
  613. var engine = this._engine;
  614. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  615. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  616. }
  617. else {
  618. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  619. }
  620. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  621. if (engine.supportsUniformBuffers) {
  622. for (var name in this._uniformBuffersNames) {
  623. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  624. }
  625. }
  626. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  627. this._attributes = engine.getAttributes(this._program, attributesNames);
  628. var index;
  629. for (index = 0; index < this._samplers.length; index++) {
  630. var sampler = this.getUniform(this._samplers[index]);
  631. if (sampler == null) {
  632. this._samplers.splice(index, 1);
  633. index--;
  634. }
  635. }
  636. engine.bindSamplers(this);
  637. this._compilationError = "";
  638. this._isReady = true;
  639. if (this.onCompiled) {
  640. this.onCompiled(this);
  641. }
  642. this.onCompileObservable.notifyObservers(this);
  643. this.onCompileObservable.clear();
  644. // Unbind mesh reference in fallbacks
  645. if (this._fallbacks) {
  646. this._fallbacks.unBindMesh();
  647. }
  648. if (previousProgram) {
  649. this.getEngine()._deleteProgram(previousProgram);
  650. }
  651. }
  652. catch (e) {
  653. this._compilationError = e.message;
  654. // Let's go through fallbacks then
  655. BABYLON.Tools.Error("Unable to compile effect:");
  656. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  657. return " " + uniform;
  658. }));
  659. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  660. return " " + attribute;
  661. }));
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6093. };
  6094. /**
  6095. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8129. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._deferUnregister(observer);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._deferUnregister(this._observers[index]);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this._remove(observer);
  8218. });
  8219. };
  8220. // This should only be called when not iterating over _observers to avoid callback skipping.
  8221. // Removes an observer from the _observer Array.
  8222. Observable.prototype._remove = function (observer) {
  8223. if (!observer) {
  8224. return false;
  8225. }
  8226. var index = this._observers.indexOf(observer);
  8227. if (index !== -1) {
  8228. this._observers.splice(index, 1);
  8229. return true;
  8230. }
  8231. return false;
  8232. };
  8233. /**
  8234. * Notify all Observers by calling their respective callback with the given data
  8235. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8236. * @param eventData defines the data to send to all observers
  8237. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8238. * @param target defines the original target of the state
  8239. * @param currentTarget defines the current target of the state
  8240. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8241. */
  8242. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8243. if (mask === void 0) { mask = -1; }
  8244. if (!this._observers.length) {
  8245. return true;
  8246. }
  8247. var state = this._eventState;
  8248. state.mask = mask;
  8249. state.target = target;
  8250. state.currentTarget = currentTarget;
  8251. state.skipNextObservers = false;
  8252. state.lastReturnValue = eventData;
  8253. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8254. var obs = _a[_i];
  8255. if (obs._willBeUnregistered) {
  8256. continue;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8261. }
  8262. else {
  8263. state.lastReturnValue = obs.callback(eventData, state);
  8264. }
  8265. if (obs.unregisterOnNextCall) {
  8266. this._deferUnregister(obs);
  8267. }
  8268. }
  8269. if (state.skipNextObservers) {
  8270. return false;
  8271. }
  8272. }
  8273. return true;
  8274. };
  8275. /**
  8276. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8277. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8278. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8279. * and it is crucial that all callbacks will be executed.
  8280. * The order of the callbacks is kept, callbacks are not executed parallel.
  8281. *
  8282. * @param eventData The data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. * @param target defines the callback target (see EventState)
  8285. * @param currentTarget defines he current object in the bubbling phase
  8286. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8287. */
  8288. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8289. var _this = this;
  8290. if (mask === void 0) { mask = -1; }
  8291. // create an empty promise
  8292. var p = Promise.resolve(eventData);
  8293. // no observers? return this promise.
  8294. if (!this._observers.length) {
  8295. return p;
  8296. }
  8297. var state = this._eventState;
  8298. state.mask = mask;
  8299. state.target = target;
  8300. state.currentTarget = currentTarget;
  8301. state.skipNextObservers = false;
  8302. // execute one callback after another (not using Promise.all, the order is important)
  8303. this._observers.forEach(function (obs) {
  8304. if (state.skipNextObservers) {
  8305. return;
  8306. }
  8307. if (obs._willBeUnregistered) {
  8308. return;
  8309. }
  8310. if (obs.mask & mask) {
  8311. if (obs.scope) {
  8312. p = p.then(function (lastReturnedValue) {
  8313. state.lastReturnValue = lastReturnedValue;
  8314. return obs.callback.apply(obs.scope, [eventData, state]);
  8315. });
  8316. }
  8317. else {
  8318. p = p.then(function (lastReturnedValue) {
  8319. state.lastReturnValue = lastReturnedValue;
  8320. return obs.callback(eventData, state);
  8321. });
  8322. }
  8323. if (obs.unregisterOnNextCall) {
  8324. _this._deferUnregister(obs);
  8325. }
  8326. }
  8327. });
  8328. // return the eventData
  8329. return p.then(function () { return eventData; });
  8330. };
  8331. /**
  8332. * Notify a specific observer
  8333. * @param observer defines the observer to notify
  8334. * @param eventData defines the data to be sent to each callback
  8335. * @param mask is used to filter observers defaults to -1
  8336. */
  8337. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8338. if (mask === void 0) { mask = -1; }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.skipNextObservers = false;
  8342. observer.callback(eventData, state);
  8343. };
  8344. /**
  8345. * Gets a boolean indicating if the observable has at least one observer
  8346. * @returns true is the Observable has at least one Observer registered
  8347. */
  8348. Observable.prototype.hasObservers = function () {
  8349. return this._observers.length > 0;
  8350. };
  8351. /**
  8352. * Clear the list of observers
  8353. */
  8354. Observable.prototype.clear = function () {
  8355. this._observers = new Array();
  8356. this._onObserverAdded = null;
  8357. };
  8358. /**
  8359. * Clone the current observable
  8360. * @returns a new observable
  8361. */
  8362. Observable.prototype.clone = function () {
  8363. var result = new Observable();
  8364. result._observers = this._observers.slice(0);
  8365. return result;
  8366. };
  8367. /**
  8368. * Does this observable handles observer registered with a given mask
  8369. * @param mask defines the mask to be tested
  8370. * @return whether or not one observer registered with the given mask is handeled
  8371. **/
  8372. Observable.prototype.hasSpecificMask = function (mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8375. var obs = _a[_i];
  8376. if (obs.mask & mask || obs.mask === mask) {
  8377. return true;
  8378. }
  8379. }
  8380. return false;
  8381. };
  8382. return Observable;
  8383. }());
  8384. BABYLON.Observable = Observable;
  8385. })(BABYLON || (BABYLON = {}));
  8386. //# sourceMappingURL=babylon.observable.js.map
  8387. var BABYLON;
  8388. (function (BABYLON) {
  8389. var SmartArray = /** @class */ (function () {
  8390. function SmartArray(capacity) {
  8391. this.length = 0;
  8392. this.data = new Array(capacity);
  8393. this._id = SmartArray._GlobalId++;
  8394. }
  8395. SmartArray.prototype.push = function (value) {
  8396. this.data[this.length++] = value;
  8397. if (this.length > this.data.length) {
  8398. this.data.length *= 2;
  8399. }
  8400. };
  8401. SmartArray.prototype.forEach = function (func) {
  8402. for (var index = 0; index < this.length; index++) {
  8403. func(this.data[index]);
  8404. }
  8405. };
  8406. SmartArray.prototype.sort = function (compareFn) {
  8407. this.data.sort(compareFn);
  8408. };
  8409. SmartArray.prototype.reset = function () {
  8410. this.length = 0;
  8411. };
  8412. SmartArray.prototype.dispose = function () {
  8413. this.reset();
  8414. if (this.data) {
  8415. this.data.length = 0;
  8416. this.data = [];
  8417. }
  8418. };
  8419. SmartArray.prototype.concat = function (array) {
  8420. if (array.length === 0) {
  8421. return;
  8422. }
  8423. if (this.length + array.length > this.data.length) {
  8424. this.data.length = (this.length + array.length) * 2;
  8425. }
  8426. for (var index = 0; index < array.length; index++) {
  8427. this.data[this.length++] = (array.data || array)[index];
  8428. }
  8429. };
  8430. SmartArray.prototype.indexOf = function (value) {
  8431. var position = this.data.indexOf(value);
  8432. if (position >= this.length) {
  8433. return -1;
  8434. }
  8435. return position;
  8436. };
  8437. SmartArray.prototype.contains = function (value) {
  8438. return this.data.indexOf(value) !== -1;
  8439. };
  8440. // Statics
  8441. SmartArray._GlobalId = 0;
  8442. return SmartArray;
  8443. }());
  8444. BABYLON.SmartArray = SmartArray;
  8445. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8446. __extends(SmartArrayNoDuplicate, _super);
  8447. function SmartArrayNoDuplicate() {
  8448. var _this = _super !== null && _super.apply(this, arguments) || this;
  8449. _this._duplicateId = 0;
  8450. return _this;
  8451. }
  8452. SmartArrayNoDuplicate.prototype.push = function (value) {
  8453. _super.prototype.push.call(this, value);
  8454. if (!value.__smartArrayFlags) {
  8455. value.__smartArrayFlags = {};
  8456. }
  8457. value.__smartArrayFlags[this._id] = this._duplicateId;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8460. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8461. return false;
  8462. }
  8463. this.push(value);
  8464. return true;
  8465. };
  8466. SmartArrayNoDuplicate.prototype.reset = function () {
  8467. _super.prototype.reset.call(this);
  8468. this._duplicateId++;
  8469. };
  8470. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8471. if (array.length === 0) {
  8472. return;
  8473. }
  8474. if (this.length + array.length > this.data.length) {
  8475. this.data.length = (this.length + array.length) * 2;
  8476. }
  8477. for (var index = 0; index < array.length; index++) {
  8478. var item = (array.data || array)[index];
  8479. this.pushNoDuplicate(item);
  8480. }
  8481. };
  8482. return SmartArrayNoDuplicate;
  8483. }(SmartArray));
  8484. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.smartArray.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. /** Class used to store color gradient */
  8490. var ColorGradient = /** @class */ (function () {
  8491. function ColorGradient() {
  8492. }
  8493. /**
  8494. * Will get a color picked randomly between color1 and color2.
  8495. * If color2 is undefined then color1 will be used
  8496. * @param result defines the target Color4 to store the result in
  8497. */
  8498. ColorGradient.prototype.getColorToRef = function (result) {
  8499. if (!this.color2) {
  8500. result.copyFrom(this.color1);
  8501. return;
  8502. }
  8503. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8504. };
  8505. return ColorGradient;
  8506. }());
  8507. BABYLON.ColorGradient = ColorGradient;
  8508. /** Class used to store factor gradient */
  8509. var FactorGradient = /** @class */ (function () {
  8510. function FactorGradient() {
  8511. }
  8512. /**
  8513. * Will get a number picked randomly between factor1 and factor2.
  8514. * If factor2 is undefined then factor1 will be used
  8515. * @returns the picked number
  8516. */
  8517. FactorGradient.prototype.getFactor = function () {
  8518. if (this.factor2 === undefined) {
  8519. return this.factor1;
  8520. }
  8521. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8522. };
  8523. return FactorGradient;
  8524. }());
  8525. BABYLON.FactorGradient = FactorGradient;
  8526. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8527. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8528. var LoadFileError = /** @class */ (function (_super) {
  8529. __extends(LoadFileError, _super);
  8530. function LoadFileError(message, request) {
  8531. var _this = _super.call(this, message) || this;
  8532. _this.request = request;
  8533. _this.name = "LoadFileError";
  8534. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8535. return _this;
  8536. }
  8537. // Polyfill for Object.setPrototypeOf if necessary.
  8538. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8539. return LoadFileError;
  8540. }(Error));
  8541. BABYLON.LoadFileError = LoadFileError;
  8542. var RetryStrategy = /** @class */ (function () {
  8543. function RetryStrategy() {
  8544. }
  8545. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8546. if (maxRetries === void 0) { maxRetries = 3; }
  8547. if (baseInterval === void 0) { baseInterval = 500; }
  8548. return function (url, request, retryIndex) {
  8549. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8550. return -1;
  8551. }
  8552. return Math.pow(2, retryIndex) * baseInterval;
  8553. };
  8554. };
  8555. return RetryStrategy;
  8556. }());
  8557. BABYLON.RetryStrategy = RetryStrategy;
  8558. // Screenshots
  8559. var screenshotCanvas;
  8560. var cloneValue = function (source, destinationObject) {
  8561. if (!source)
  8562. return null;
  8563. if (source instanceof BABYLON.Mesh) {
  8564. return null;
  8565. }
  8566. if (source instanceof BABYLON.SubMesh) {
  8567. return source.clone(destinationObject);
  8568. }
  8569. else if (source.clone) {
  8570. return source.clone();
  8571. }
  8572. return null;
  8573. };
  8574. var Tools = /** @class */ (function () {
  8575. function Tools() {
  8576. }
  8577. /**
  8578. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8579. * @param u defines the coordinate on X axis
  8580. * @param v defines the coordinate on Y axis
  8581. * @param width defines the width of the source data
  8582. * @param height defines the height of the source data
  8583. * @param pixels defines the source byte array
  8584. * @param color defines the output color
  8585. */
  8586. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8587. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8588. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8589. var position = (wrappedU + wrappedV * width) * 4;
  8590. color.r = pixels[position] / 255;
  8591. color.g = pixels[position + 1] / 255;
  8592. color.b = pixels[position + 2] / 255;
  8593. color.a = pixels[position + 3] / 255;
  8594. };
  8595. /**
  8596. * Interpolates between a and b via alpha
  8597. * @param a The lower value (returned when alpha = 0)
  8598. * @param b The upper value (returned when alpha = 1)
  8599. * @param alpha The interpolation-factor
  8600. * @return The mixed value
  8601. */
  8602. Tools.Mix = function (a, b, alpha) {
  8603. return a * (1 - alpha) + b * alpha;
  8604. };
  8605. Tools.Instantiate = function (className) {
  8606. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8607. return Tools.RegisteredExternalClasses[className];
  8608. }
  8609. var arr = className.split(".");
  8610. var fn = (window || this);
  8611. for (var i = 0, len = arr.length; i < len; i++) {
  8612. fn = fn[arr[i]];
  8613. }
  8614. if (typeof fn !== "function") {
  8615. return null;
  8616. }
  8617. return fn;
  8618. };
  8619. /**
  8620. * Provides a slice function that will work even on IE
  8621. * @param data defines the array to slice
  8622. * @param start defines the start of the data (optional)
  8623. * @param end defines the end of the data (optional)
  8624. * @returns the new sliced array
  8625. */
  8626. Tools.Slice = function (data, start, end) {
  8627. if (data.slice) {
  8628. return data.slice(start, end);
  8629. }
  8630. return Array.prototype.slice.call(data, start, end);
  8631. };
  8632. Tools.SetImmediate = function (action) {
  8633. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8634. window.setImmediate(action);
  8635. }
  8636. else {
  8637. setTimeout(action, 1);
  8638. }
  8639. };
  8640. Tools.IsExponentOfTwo = function (value) {
  8641. var count = 1;
  8642. do {
  8643. count *= 2;
  8644. } while (count < value);
  8645. return count === value;
  8646. };
  8647. /**
  8648. * Returns the nearest 32-bit single precision float representation of a Number
  8649. * @param value A Number. If the parameter is of a different type, it will get converted
  8650. * to a number or to NaN if it cannot be converted
  8651. * @returns number
  8652. */
  8653. Tools.FloatRound = function (value) {
  8654. if (Math.fround) {
  8655. return Math.fround(value);
  8656. }
  8657. return (Tools._tmpFloatArray[0] = value);
  8658. };
  8659. /**
  8660. * Find the next highest power of two.
  8661. * @param x Number to start search from.
  8662. * @return Next highest power of two.
  8663. */
  8664. Tools.CeilingPOT = function (x) {
  8665. x--;
  8666. x |= x >> 1;
  8667. x |= x >> 2;
  8668. x |= x >> 4;
  8669. x |= x >> 8;
  8670. x |= x >> 16;
  8671. x++;
  8672. return x;
  8673. };
  8674. /**
  8675. * Find the next lowest power of two.
  8676. * @param x Number to start search from.
  8677. * @return Next lowest power of two.
  8678. */
  8679. Tools.FloorPOT = function (x) {
  8680. x = x | (x >> 1);
  8681. x = x | (x >> 2);
  8682. x = x | (x >> 4);
  8683. x = x | (x >> 8);
  8684. x = x | (x >> 16);
  8685. return x - (x >> 1);
  8686. };
  8687. /**
  8688. * Find the nearest power of two.
  8689. * @param x Number to start search from.
  8690. * @return Next nearest power of two.
  8691. */
  8692. Tools.NearestPOT = function (x) {
  8693. var c = Tools.CeilingPOT(x);
  8694. var f = Tools.FloorPOT(x);
  8695. return (c - x) > (x - f) ? f : c;
  8696. };
  8697. Tools.GetExponentOfTwo = function (value, max, mode) {
  8698. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8699. var pot;
  8700. switch (mode) {
  8701. case BABYLON.Engine.SCALEMODE_FLOOR:
  8702. pot = Tools.FloorPOT(value);
  8703. break;
  8704. case BABYLON.Engine.SCALEMODE_NEAREST:
  8705. pot = Tools.NearestPOT(value);
  8706. break;
  8707. case BABYLON.Engine.SCALEMODE_CEILING:
  8708. default:
  8709. pot = Tools.CeilingPOT(value);
  8710. break;
  8711. }
  8712. return Math.min(pot, max);
  8713. };
  8714. Tools.GetFilename = function (path) {
  8715. var index = path.lastIndexOf("/");
  8716. if (index < 0)
  8717. return path;
  8718. return path.substring(index + 1);
  8719. };
  8720. /**
  8721. * Extracts the "folder" part of a path (everything before the filename).
  8722. * @param uri The URI to extract the info from
  8723. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8724. * @returns The "folder" part of the path
  8725. */
  8726. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8727. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8728. var index = uri.lastIndexOf("/");
  8729. if (index < 0) {
  8730. if (returnUnchangedIfNoSlash) {
  8731. return uri;
  8732. }
  8733. return "";
  8734. }
  8735. return uri.substring(0, index + 1);
  8736. };
  8737. Tools.GetDOMTextContent = function (element) {
  8738. var result = "";
  8739. var child = element.firstChild;
  8740. while (child) {
  8741. if (child.nodeType === 3) {
  8742. result += child.textContent;
  8743. }
  8744. child = child.nextSibling;
  8745. }
  8746. return result;
  8747. };
  8748. Tools.ToDegrees = function (angle) {
  8749. return angle * 180 / Math.PI;
  8750. };
  8751. Tools.ToRadians = function (angle) {
  8752. return angle * Math.PI / 180;
  8753. };
  8754. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8755. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8756. var output = "";
  8757. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8758. var i = 0;
  8759. var bytes = new Uint8Array(buffer);
  8760. while (i < bytes.length) {
  8761. chr1 = bytes[i++];
  8762. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8763. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8764. enc1 = chr1 >> 2;
  8765. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8766. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8767. enc4 = chr3 & 63;
  8768. if (isNaN(chr2)) {
  8769. enc3 = enc4 = 64;
  8770. }
  8771. else if (isNaN(chr3)) {
  8772. enc4 = 64;
  8773. }
  8774. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8775. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8776. }
  8777. return "data:image/png;base64," + output;
  8778. };
  8779. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8780. if (bias === void 0) { bias = null; }
  8781. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8782. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8783. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8784. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8785. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8786. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8787. }
  8788. if (bias) {
  8789. minimum.x -= minimum.x * bias.x + bias.y;
  8790. minimum.y -= minimum.y * bias.x + bias.y;
  8791. minimum.z -= minimum.z * bias.x + bias.y;
  8792. maximum.x += maximum.x * bias.x + bias.y;
  8793. maximum.y += maximum.y * bias.x + bias.y;
  8794. maximum.z += maximum.z * bias.x + bias.y;
  8795. }
  8796. return {
  8797. minimum: minimum,
  8798. maximum: maximum
  8799. };
  8800. };
  8801. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8802. if (bias === void 0) { bias = null; }
  8803. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8804. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8805. if (!stride) {
  8806. stride = 3;
  8807. }
  8808. for (var index = start; index < start + count; index++) {
  8809. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8810. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8811. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8812. }
  8813. if (bias) {
  8814. minimum.x -= minimum.x * bias.x + bias.y;
  8815. minimum.y -= minimum.y * bias.x + bias.y;
  8816. minimum.z -= minimum.z * bias.x + bias.y;
  8817. maximum.x += maximum.x * bias.x + bias.y;
  8818. maximum.y += maximum.y * bias.x + bias.y;
  8819. maximum.z += maximum.z * bias.x + bias.y;
  8820. }
  8821. return {
  8822. minimum: minimum,
  8823. maximum: maximum
  8824. };
  8825. };
  8826. Tools.Vector2ArrayFeeder = function (array) {
  8827. return function (index) {
  8828. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8829. var length = isFloatArray ? array.length / 2 : array.length;
  8830. if (index >= length) {
  8831. return null;
  8832. }
  8833. if (isFloatArray) {
  8834. var fa = array;
  8835. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8836. }
  8837. var a = array;
  8838. return a[index];
  8839. };
  8840. };
  8841. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8842. if (bias === void 0) { bias = null; }
  8843. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8844. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8845. var i = 0;
  8846. var cur = feeder(i++);
  8847. while (cur) {
  8848. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8849. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8850. cur = feeder(i++);
  8851. }
  8852. if (bias) {
  8853. minimum.x -= minimum.x * bias.x + bias.y;
  8854. minimum.y -= minimum.y * bias.x + bias.y;
  8855. maximum.x += maximum.x * bias.x + bias.y;
  8856. maximum.y += maximum.y * bias.x + bias.y;
  8857. }
  8858. return {
  8859. minimum: minimum,
  8860. maximum: maximum
  8861. };
  8862. };
  8863. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8864. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8865. return null;
  8866. return Array.isArray(obj) ? obj : [obj];
  8867. };
  8868. // Misc.
  8869. Tools.GetPointerPrefix = function () {
  8870. var eventPrefix = "pointer";
  8871. // Check if pointer events are supported
  8872. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8873. eventPrefix = "mouse";
  8874. }
  8875. return eventPrefix;
  8876. };
  8877. /**
  8878. * @param func - the function to be called
  8879. * @param requester - the object that will request the next frame. Falls back to window.
  8880. */
  8881. Tools.QueueNewFrame = function (func, requester) {
  8882. if (!Tools.IsWindowObjectExist()) {
  8883. return setTimeout(func, 16);
  8884. }
  8885. if (!requester) {
  8886. requester = window;
  8887. }
  8888. if (requester.requestAnimationFrame) {
  8889. return requester.requestAnimationFrame(func);
  8890. }
  8891. else if (requester.msRequestAnimationFrame) {
  8892. return requester.msRequestAnimationFrame(func);
  8893. }
  8894. else if (requester.webkitRequestAnimationFrame) {
  8895. return requester.webkitRequestAnimationFrame(func);
  8896. }
  8897. else if (requester.mozRequestAnimationFrame) {
  8898. return requester.mozRequestAnimationFrame(func);
  8899. }
  8900. else if (requester.oRequestAnimationFrame) {
  8901. return requester.oRequestAnimationFrame(func);
  8902. }
  8903. else {
  8904. return window.setTimeout(func, 16);
  8905. }
  8906. };
  8907. Tools.RequestFullscreen = function (element) {
  8908. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8909. if (!requestFunction)
  8910. return;
  8911. requestFunction.call(element);
  8912. };
  8913. Tools.ExitFullscreen = function () {
  8914. if (document.exitFullscreen) {
  8915. document.exitFullscreen();
  8916. }
  8917. else if (document.mozCancelFullScreen) {
  8918. document.mozCancelFullScreen();
  8919. }
  8920. else if (document.webkitCancelFullScreen) {
  8921. document.webkitCancelFullScreen();
  8922. }
  8923. else if (document.msCancelFullScreen) {
  8924. document.msCancelFullScreen();
  8925. }
  8926. };
  8927. Tools.SetCorsBehavior = function (url, element) {
  8928. if (url && url.indexOf("data:") === 0) {
  8929. return;
  8930. }
  8931. if (Tools.CorsBehavior) {
  8932. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8933. element.crossOrigin = Tools.CorsBehavior;
  8934. }
  8935. else {
  8936. var result = Tools.CorsBehavior(url);
  8937. if (result) {
  8938. element.crossOrigin = result;
  8939. }
  8940. }
  8941. }
  8942. };
  8943. // External files
  8944. Tools.CleanUrl = function (url) {
  8945. url = url.replace(/#/mg, "%23");
  8946. return url;
  8947. };
  8948. /**
  8949. * Loads an image as an HTMLImageElement.
  8950. * @param input url string, ArrayBuffer, or Blob to load
  8951. * @param onLoad callback called when the image successfully loads
  8952. * @param onError callback called when the image fails to load
  8953. * @param database database for caching
  8954. * @returns the HTMLImageElement of the loaded image
  8955. */
  8956. Tools.LoadImage = function (input, onLoad, onError, database) {
  8957. var url;
  8958. var usingObjectURL = false;
  8959. if (input instanceof ArrayBuffer) {
  8960. url = URL.createObjectURL(new Blob([input]));
  8961. usingObjectURL = true;
  8962. }
  8963. else if (input instanceof Blob) {
  8964. url = URL.createObjectURL(input);
  8965. usingObjectURL = true;
  8966. }
  8967. else {
  8968. url = Tools.CleanUrl(input);
  8969. url = Tools.PreprocessUrl(input);
  8970. }
  8971. var img = new Image();
  8972. Tools.SetCorsBehavior(url, img);
  8973. var loadHandler = function () {
  8974. if (usingObjectURL && img.src) {
  8975. URL.revokeObjectURL(img.src);
  8976. }
  8977. img.removeEventListener("load", loadHandler);
  8978. img.removeEventListener("error", errorHandler);
  8979. onLoad(img);
  8980. };
  8981. var errorHandler = function (err) {
  8982. if (usingObjectURL && img.src) {
  8983. URL.revokeObjectURL(img.src);
  8984. }
  8985. img.removeEventListener("load", loadHandler);
  8986. img.removeEventListener("error", errorHandler);
  8987. Tools.Error("Error while trying to load image: " + input);
  8988. if (onError) {
  8989. onError("Error while trying to load image: " + input, err);
  8990. }
  8991. };
  8992. img.addEventListener("load", loadHandler);
  8993. img.addEventListener("error", errorHandler);
  8994. var noIndexedDB = function () {
  8995. img.src = url;
  8996. };
  8997. var loadFromIndexedDB = function () {
  8998. if (database) {
  8999. database.loadImageFromDB(url, img);
  9000. }
  9001. };
  9002. //ANY database to do!
  9003. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9004. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9005. }
  9006. else {
  9007. if (url.indexOf("file:") !== -1) {
  9008. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9009. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9010. try {
  9011. var blobURL;
  9012. try {
  9013. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9014. }
  9015. catch (ex) {
  9016. // Chrome doesn't support oneTimeOnly parameter
  9017. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9018. }
  9019. img.src = blobURL;
  9020. usingObjectURL = true;
  9021. }
  9022. catch (e) {
  9023. img.src = "";
  9024. }
  9025. return img;
  9026. }
  9027. }
  9028. noIndexedDB();
  9029. }
  9030. return img;
  9031. };
  9032. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9033. url = Tools.CleanUrl(url);
  9034. url = Tools.PreprocessUrl(url);
  9035. // If file and file input are set
  9036. if (url.indexOf("file:") !== -1) {
  9037. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9038. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9039. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9040. }
  9041. }
  9042. var loadUrl = Tools.BaseUrl + url;
  9043. var aborted = false;
  9044. var fileRequest = {
  9045. onCompleteObservable: new BABYLON.Observable(),
  9046. abort: function () { return aborted = true; },
  9047. };
  9048. var requestFile = function () {
  9049. var request = new XMLHttpRequest();
  9050. var retryHandle = null;
  9051. fileRequest.abort = function () {
  9052. aborted = true;
  9053. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9054. request.abort();
  9055. }
  9056. if (retryHandle !== null) {
  9057. clearTimeout(retryHandle);
  9058. retryHandle = null;
  9059. }
  9060. };
  9061. var retryLoop = function (retryIndex) {
  9062. request.open('GET', loadUrl, true);
  9063. if (useArrayBuffer) {
  9064. request.responseType = "arraybuffer";
  9065. }
  9066. if (onProgress) {
  9067. request.addEventListener("progress", onProgress);
  9068. }
  9069. var onLoadEnd = function () {
  9070. request.removeEventListener("loadend", onLoadEnd);
  9071. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9072. fileRequest.onCompleteObservable.clear();
  9073. };
  9074. request.addEventListener("loadend", onLoadEnd);
  9075. var onReadyStateChange = function () {
  9076. if (aborted) {
  9077. return;
  9078. }
  9079. // In case of undefined state in some browsers.
  9080. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9081. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9082. request.removeEventListener("readystatechange", onReadyStateChange);
  9083. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9084. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9085. return;
  9086. }
  9087. var retryStrategy = Tools.DefaultRetryStrategy;
  9088. if (retryStrategy) {
  9089. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9090. if (waitTime !== -1) {
  9091. // Prevent the request from completing for retry.
  9092. request.removeEventListener("loadend", onLoadEnd);
  9093. request = new XMLHttpRequest();
  9094. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9095. return;
  9096. }
  9097. }
  9098. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9099. if (onError) {
  9100. onError(request, e);
  9101. }
  9102. else {
  9103. throw e;
  9104. }
  9105. }
  9106. };
  9107. request.addEventListener("readystatechange", onReadyStateChange);
  9108. request.send();
  9109. };
  9110. retryLoop(0);
  9111. };
  9112. // Caching all files
  9113. if (database && database.enableSceneOffline) {
  9114. var noIndexedDB_1 = function (request) {
  9115. if (request && request.status > 400) {
  9116. if (onError) {
  9117. onError(request);
  9118. }
  9119. }
  9120. else {
  9121. if (!aborted) {
  9122. requestFile();
  9123. }
  9124. }
  9125. };
  9126. var loadFromIndexedDB = function () {
  9127. // TODO: database needs to support aborting and should return a IFileRequest
  9128. if (aborted) {
  9129. return;
  9130. }
  9131. if (database) {
  9132. database.loadFileFromDB(url, function (data) {
  9133. if (!aborted) {
  9134. onSuccess(data);
  9135. }
  9136. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9137. }, onProgress ? function (event) {
  9138. if (!aborted) {
  9139. onProgress(event);
  9140. }
  9141. } : undefined, noIndexedDB_1, useArrayBuffer);
  9142. }
  9143. };
  9144. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9145. }
  9146. else {
  9147. requestFile();
  9148. }
  9149. return fileRequest;
  9150. };
  9151. /**
  9152. * Load a script (identified by an url). When the url returns, the
  9153. * content of this file is added into a new script element, attached to the DOM (body element)
  9154. */
  9155. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9156. var head = document.getElementsByTagName('head')[0];
  9157. var script = document.createElement('script');
  9158. script.type = 'text/javascript';
  9159. script.src = scriptUrl;
  9160. script.onload = function () {
  9161. if (onSuccess) {
  9162. onSuccess();
  9163. }
  9164. };
  9165. script.onerror = function (e) {
  9166. if (onError) {
  9167. onError("Unable to load script '" + scriptUrl + "'", e);
  9168. }
  9169. };
  9170. head.appendChild(script);
  9171. };
  9172. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9173. var reader = new FileReader();
  9174. var request = {
  9175. onCompleteObservable: new BABYLON.Observable(),
  9176. abort: function () { return reader.abort(); },
  9177. };
  9178. reader.onloadend = function (e) {
  9179. request.onCompleteObservable.notifyObservers(request);
  9180. };
  9181. reader.onload = function (e) {
  9182. //target doesn't have result from ts 1.3
  9183. callback(e.target['result']);
  9184. };
  9185. reader.onprogress = progressCallback;
  9186. reader.readAsDataURL(fileToLoad);
  9187. return request;
  9188. };
  9189. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9190. var reader = new FileReader();
  9191. var request = {
  9192. onCompleteObservable: new BABYLON.Observable(),
  9193. abort: function () { return reader.abort(); },
  9194. };
  9195. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9196. reader.onerror = function (e) {
  9197. Tools.Log("Error while reading file: " + fileToLoad.name);
  9198. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9199. };
  9200. reader.onload = function (e) {
  9201. //target doesn't have result from ts 1.3
  9202. callback(e.target['result']);
  9203. };
  9204. if (progressCallBack) {
  9205. reader.onprogress = progressCallBack;
  9206. }
  9207. if (!useArrayBuffer) {
  9208. // Asynchronous read
  9209. reader.readAsText(fileToLoad);
  9210. }
  9211. else {
  9212. reader.readAsArrayBuffer(fileToLoad);
  9213. }
  9214. return request;
  9215. };
  9216. //returns a downloadable url to a file content.
  9217. Tools.FileAsURL = function (content) {
  9218. var fileBlob = new Blob([content]);
  9219. var url = window.URL || window.webkitURL;
  9220. var link = url.createObjectURL(fileBlob);
  9221. return link;
  9222. };
  9223. // Misc.
  9224. Tools.Format = function (value, decimals) {
  9225. if (decimals === void 0) { decimals = 2; }
  9226. return value.toFixed(decimals);
  9227. };
  9228. Tools.CheckExtends = function (v, min, max) {
  9229. if (v.x < min.x)
  9230. min.x = v.x;
  9231. if (v.y < min.y)
  9232. min.y = v.y;
  9233. if (v.z < min.z)
  9234. min.z = v.z;
  9235. if (v.x > max.x)
  9236. max.x = v.x;
  9237. if (v.y > max.y)
  9238. max.y = v.y;
  9239. if (v.z > max.z)
  9240. max.z = v.z;
  9241. };
  9242. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9243. for (var prop in source) {
  9244. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9245. continue;
  9246. }
  9247. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9248. continue;
  9249. }
  9250. var sourceValue = source[prop];
  9251. var typeOfSourceValue = typeof sourceValue;
  9252. if (typeOfSourceValue === "function") {
  9253. continue;
  9254. }
  9255. try {
  9256. if (typeOfSourceValue === "object") {
  9257. if (sourceValue instanceof Array) {
  9258. destination[prop] = [];
  9259. if (sourceValue.length > 0) {
  9260. if (typeof sourceValue[0] == "object") {
  9261. for (var index = 0; index < sourceValue.length; index++) {
  9262. var clonedValue = cloneValue(sourceValue[index], destination);
  9263. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9264. destination[prop].push(clonedValue);
  9265. }
  9266. }
  9267. }
  9268. else {
  9269. destination[prop] = sourceValue.slice(0);
  9270. }
  9271. }
  9272. }
  9273. else {
  9274. destination[prop] = cloneValue(sourceValue, destination);
  9275. }
  9276. }
  9277. else {
  9278. destination[prop] = sourceValue;
  9279. }
  9280. }
  9281. catch (e) {
  9282. // Just ignore error (it could be because of a read-only property)
  9283. }
  9284. }
  9285. };
  9286. Tools.IsEmpty = function (obj) {
  9287. for (var i in obj) {
  9288. if (obj.hasOwnProperty(i)) {
  9289. return false;
  9290. }
  9291. }
  9292. return true;
  9293. };
  9294. Tools.RegisterTopRootEvents = function (events) {
  9295. for (var index = 0; index < events.length; index++) {
  9296. var event = events[index];
  9297. window.addEventListener(event.name, event.handler, false);
  9298. try {
  9299. if (window.parent) {
  9300. window.parent.addEventListener(event.name, event.handler, false);
  9301. }
  9302. }
  9303. catch (e) {
  9304. // Silently fails...
  9305. }
  9306. }
  9307. };
  9308. Tools.UnregisterTopRootEvents = function (events) {
  9309. for (var index = 0; index < events.length; index++) {
  9310. var event = events[index];
  9311. window.removeEventListener(event.name, event.handler);
  9312. try {
  9313. if (window.parent) {
  9314. window.parent.removeEventListener(event.name, event.handler);
  9315. }
  9316. }
  9317. catch (e) {
  9318. // Silently fails...
  9319. }
  9320. }
  9321. };
  9322. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9323. if (mimeType === void 0) { mimeType = "image/png"; }
  9324. // Read the contents of the framebuffer
  9325. var numberOfChannelsByLine = width * 4;
  9326. var halfHeight = height / 2;
  9327. //Reading datas from WebGL
  9328. var data = engine.readPixels(0, 0, width, height);
  9329. //To flip image on Y axis.
  9330. for (var i = 0; i < halfHeight; i++) {
  9331. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9332. var currentCell = j + i * numberOfChannelsByLine;
  9333. var targetLine = height - i - 1;
  9334. var targetCell = j + targetLine * numberOfChannelsByLine;
  9335. var temp = data[currentCell];
  9336. data[currentCell] = data[targetCell];
  9337. data[targetCell] = temp;
  9338. }
  9339. }
  9340. // Create a 2D canvas to store the result
  9341. if (!screenshotCanvas) {
  9342. screenshotCanvas = document.createElement('canvas');
  9343. }
  9344. screenshotCanvas.width = width;
  9345. screenshotCanvas.height = height;
  9346. var context = screenshotCanvas.getContext('2d');
  9347. if (context) {
  9348. // Copy the pixels to a 2D canvas
  9349. var imageData = context.createImageData(width, height);
  9350. var castData = (imageData.data);
  9351. castData.set(data);
  9352. context.putImageData(imageData, 0, 0);
  9353. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9354. }
  9355. };
  9356. /**
  9357. * Converts the canvas data to blob.
  9358. * This acts as a polyfill for browsers not supporting the to blob function.
  9359. * @param canvas Defines the canvas to extract the data from
  9360. * @param successCallback Defines the callback triggered once the data are available
  9361. * @param mimeType Defines the mime type of the result
  9362. */
  9363. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9364. if (mimeType === void 0) { mimeType = "image/png"; }
  9365. // We need HTMLCanvasElement.toBlob for HD screenshots
  9366. if (!canvas.toBlob) {
  9367. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9368. canvas.toBlob = function (callback, type, quality) {
  9369. var _this = this;
  9370. setTimeout(function () {
  9371. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9372. for (var i = 0; i < len; i++) {
  9373. arr[i] = binStr.charCodeAt(i);
  9374. }
  9375. callback(new Blob([arr]));
  9376. });
  9377. };
  9378. }
  9379. canvas.toBlob(function (blob) {
  9380. successCallback(blob);
  9381. }, mimeType);
  9382. };
  9383. /**
  9384. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9385. * @param successCallback Defines the callback triggered once the data are available
  9386. * @param mimeType Defines the mime type of the result
  9387. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9388. */
  9389. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9390. if (mimeType === void 0) { mimeType = "image/png"; }
  9391. if (successCallback) {
  9392. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9393. successCallback(base64Image);
  9394. }
  9395. else {
  9396. this.ToBlob(screenshotCanvas, function (blob) {
  9397. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9398. if (("download" in document.createElement("a"))) {
  9399. if (!fileName) {
  9400. var date = new Date();
  9401. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9402. fileName = "screenshot_" + stringDate + ".png";
  9403. }
  9404. Tools.Download(blob, fileName);
  9405. }
  9406. else {
  9407. var url = URL.createObjectURL(blob);
  9408. var newWindow = window.open("");
  9409. if (!newWindow)
  9410. return;
  9411. var img = newWindow.document.createElement("img");
  9412. img.onload = function () {
  9413. // no longer need to read the blob so it's revoked
  9414. URL.revokeObjectURL(url);
  9415. };
  9416. img.src = url;
  9417. newWindow.document.body.appendChild(img);
  9418. }
  9419. }, mimeType);
  9420. }
  9421. };
  9422. /**
  9423. * Downloads a blob in the browser
  9424. * @param blob defines the blob to download
  9425. * @param fileName defines the name of the downloaded file
  9426. */
  9427. Tools.Download = function (blob, fileName) {
  9428. if (navigator && navigator.msSaveBlob) {
  9429. navigator.msSaveBlob(blob, fileName);
  9430. return;
  9431. }
  9432. var url = window.URL.createObjectURL(blob);
  9433. var a = document.createElement("a");
  9434. document.body.appendChild(a);
  9435. a.style.display = "none";
  9436. a.href = url;
  9437. a.download = fileName;
  9438. a.addEventListener("click", function () {
  9439. if (a.parentElement) {
  9440. a.parentElement.removeChild(a);
  9441. }
  9442. });
  9443. a.click();
  9444. window.URL.revokeObjectURL(url);
  9445. };
  9446. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9447. if (mimeType === void 0) { mimeType = "image/png"; }
  9448. var width;
  9449. var height;
  9450. // If a precision value is specified
  9451. if (size.precision) {
  9452. width = Math.round(engine.getRenderWidth() * size.precision);
  9453. height = Math.round(width / engine.getAspectRatio(camera));
  9454. }
  9455. else if (size.width && size.height) {
  9456. width = size.width;
  9457. height = size.height;
  9458. }
  9459. //If passing only width, computing height to keep display canvas ratio.
  9460. else if (size.width && !size.height) {
  9461. width = size.width;
  9462. height = Math.round(width / engine.getAspectRatio(camera));
  9463. }
  9464. //If passing only height, computing width to keep display canvas ratio.
  9465. else if (size.height && !size.width) {
  9466. height = size.height;
  9467. width = Math.round(height * engine.getAspectRatio(camera));
  9468. }
  9469. //Assuming here that "size" parameter is a number
  9470. else if (!isNaN(size)) {
  9471. height = size;
  9472. width = size;
  9473. }
  9474. else {
  9475. Tools.Error("Invalid 'size' parameter !");
  9476. return;
  9477. }
  9478. if (!screenshotCanvas) {
  9479. screenshotCanvas = document.createElement('canvas');
  9480. }
  9481. screenshotCanvas.width = width;
  9482. screenshotCanvas.height = height;
  9483. var renderContext = screenshotCanvas.getContext("2d");
  9484. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9485. var newWidth = width;
  9486. var newHeight = newWidth / ratio;
  9487. if (newHeight > height) {
  9488. newHeight = height;
  9489. newWidth = newHeight * ratio;
  9490. }
  9491. var offsetX = Math.max(0, width - newWidth) / 2;
  9492. var offsetY = Math.max(0, height - newHeight) / 2;
  9493. var renderingCanvas = engine.getRenderingCanvas();
  9494. if (renderContext && renderingCanvas) {
  9495. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9496. }
  9497. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9498. };
  9499. /**
  9500. * Generates an image screenshot from the specified camera.
  9501. *
  9502. * @param engine The engine to use for rendering
  9503. * @param camera The camera to use for rendering
  9504. * @param size This parameter can be set to a single number or to an object with the
  9505. * following (optional) properties: precision, width, height. If a single number is passed,
  9506. * it will be used for both width and height. If an object is passed, the screenshot size
  9507. * will be derived from the parameters. The precision property is a multiplier allowing
  9508. * rendering at a higher or lower resolution.
  9509. * @param successCallback The callback receives a single parameter which contains the
  9510. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9511. * src parameter of an <img> to display it.
  9512. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9513. * Check your browser for supported MIME types.
  9514. * @param samples Texture samples (default: 1)
  9515. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9516. * @param fileName A name for for the downloaded file.
  9517. * @constructor
  9518. */
  9519. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9520. if (mimeType === void 0) { mimeType = "image/png"; }
  9521. if (samples === void 0) { samples = 1; }
  9522. if (antialiasing === void 0) { antialiasing = false; }
  9523. var width;
  9524. var height;
  9525. //If a precision value is specified
  9526. if (size.precision) {
  9527. width = Math.round(engine.getRenderWidth() * size.precision);
  9528. height = Math.round(width / engine.getAspectRatio(camera));
  9529. size = { width: width, height: height };
  9530. }
  9531. else if (size.width && size.height) {
  9532. width = size.width;
  9533. height = size.height;
  9534. }
  9535. //If passing only width, computing height to keep display canvas ratio.
  9536. else if (size.width && !size.height) {
  9537. width = size.width;
  9538. height = Math.round(width / engine.getAspectRatio(camera));
  9539. size = { width: width, height: height };
  9540. }
  9541. //If passing only height, computing width to keep display canvas ratio.
  9542. else if (size.height && !size.width) {
  9543. height = size.height;
  9544. width = Math.round(height * engine.getAspectRatio(camera));
  9545. size = { width: width, height: height };
  9546. }
  9547. //Assuming here that "size" parameter is a number
  9548. else if (!isNaN(size)) {
  9549. height = size;
  9550. width = size;
  9551. }
  9552. else {
  9553. Tools.Error("Invalid 'size' parameter !");
  9554. return;
  9555. }
  9556. var scene = camera.getScene();
  9557. var previousCamera = null;
  9558. if (scene.activeCamera !== camera) {
  9559. previousCamera = scene.activeCamera;
  9560. scene.activeCamera = camera;
  9561. }
  9562. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9563. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9564. texture.renderList = null;
  9565. texture.samples = samples;
  9566. if (antialiasing) {
  9567. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9568. }
  9569. texture.onAfterRenderObservable.add(function () {
  9570. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9571. });
  9572. scene.incrementRenderId();
  9573. scene.resetCachedMaterial();
  9574. texture.render(true);
  9575. texture.dispose();
  9576. if (previousCamera) {
  9577. scene.activeCamera = previousCamera;
  9578. }
  9579. camera.getProjectionMatrix(true); // Force cache refresh;
  9580. };
  9581. // XHR response validator for local file scenario
  9582. Tools.ValidateXHRData = function (xhr, dataType) {
  9583. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9584. if (dataType === void 0) { dataType = 7; }
  9585. try {
  9586. if (dataType & 1) {
  9587. if (xhr.responseText && xhr.responseText.length > 0) {
  9588. return true;
  9589. }
  9590. else if (dataType === 1) {
  9591. return false;
  9592. }
  9593. }
  9594. if (dataType & 2) {
  9595. // Check header width and height since there is no "TGA" magic number
  9596. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9597. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9598. return true;
  9599. }
  9600. else if (dataType === 2) {
  9601. return false;
  9602. }
  9603. }
  9604. if (dataType & 4) {
  9605. // Check for the "DDS" magic number
  9606. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9607. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9608. return true;
  9609. }
  9610. else {
  9611. return false;
  9612. }
  9613. }
  9614. }
  9615. catch (e) {
  9616. // Global protection
  9617. }
  9618. return false;
  9619. };
  9620. /**
  9621. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9622. * Be aware Math.random() could cause collisions, but:
  9623. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9624. */
  9625. Tools.RandomId = function () {
  9626. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9627. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9628. return v.toString(16);
  9629. });
  9630. };
  9631. /**
  9632. * Test if the given uri is a base64 string.
  9633. * @param uri The uri to test
  9634. * @return True if the uri is a base64 string or false otherwise.
  9635. */
  9636. Tools.IsBase64 = function (uri) {
  9637. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9638. };
  9639. /**
  9640. * Decode the given base64 uri.
  9641. * @param uri The uri to decode
  9642. * @return The decoded base64 data.
  9643. */
  9644. Tools.DecodeBase64 = function (uri) {
  9645. var decodedString = atob(uri.split(",")[1]);
  9646. var bufferLength = decodedString.length;
  9647. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9648. for (var i = 0; i < bufferLength; i++) {
  9649. bufferView[i] = decodedString.charCodeAt(i);
  9650. }
  9651. return bufferView.buffer;
  9652. };
  9653. Object.defineProperty(Tools, "NoneLogLevel", {
  9654. get: function () {
  9655. return Tools._NoneLogLevel;
  9656. },
  9657. enumerable: true,
  9658. configurable: true
  9659. });
  9660. Object.defineProperty(Tools, "MessageLogLevel", {
  9661. get: function () {
  9662. return Tools._MessageLogLevel;
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. Object.defineProperty(Tools, "WarningLogLevel", {
  9668. get: function () {
  9669. return Tools._WarningLogLevel;
  9670. },
  9671. enumerable: true,
  9672. configurable: true
  9673. });
  9674. Object.defineProperty(Tools, "ErrorLogLevel", {
  9675. get: function () {
  9676. return Tools._ErrorLogLevel;
  9677. },
  9678. enumerable: true,
  9679. configurable: true
  9680. });
  9681. Object.defineProperty(Tools, "AllLogLevel", {
  9682. get: function () {
  9683. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9684. },
  9685. enumerable: true,
  9686. configurable: true
  9687. });
  9688. Tools._AddLogEntry = function (entry) {
  9689. Tools._LogCache = entry + Tools._LogCache;
  9690. if (Tools.OnNewCacheEntry) {
  9691. Tools.OnNewCacheEntry(entry);
  9692. }
  9693. };
  9694. Tools._FormatMessage = function (message) {
  9695. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9696. var date = new Date();
  9697. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9698. };
  9699. Tools._LogDisabled = function (message) {
  9700. // nothing to do
  9701. };
  9702. Tools._LogEnabled = function (message) {
  9703. var formattedMessage = Tools._FormatMessage(message);
  9704. console.log("BJS - " + formattedMessage);
  9705. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9706. Tools._AddLogEntry(entry);
  9707. };
  9708. Tools._WarnDisabled = function (message) {
  9709. // nothing to do
  9710. };
  9711. Tools._WarnEnabled = function (message) {
  9712. var formattedMessage = Tools._FormatMessage(message);
  9713. console.warn("BJS - " + formattedMessage);
  9714. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9715. Tools._AddLogEntry(entry);
  9716. };
  9717. Tools._ErrorDisabled = function (message) {
  9718. // nothing to do
  9719. };
  9720. Tools._ErrorEnabled = function (message) {
  9721. Tools.errorsCount++;
  9722. var formattedMessage = Tools._FormatMessage(message);
  9723. console.error("BJS - " + formattedMessage);
  9724. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9725. Tools._AddLogEntry(entry);
  9726. };
  9727. Object.defineProperty(Tools, "LogCache", {
  9728. get: function () {
  9729. return Tools._LogCache;
  9730. },
  9731. enumerable: true,
  9732. configurable: true
  9733. });
  9734. Tools.ClearLogCache = function () {
  9735. Tools._LogCache = "";
  9736. Tools.errorsCount = 0;
  9737. };
  9738. Object.defineProperty(Tools, "LogLevels", {
  9739. set: function (level) {
  9740. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9741. Tools.Log = Tools._LogEnabled;
  9742. }
  9743. else {
  9744. Tools.Log = Tools._LogDisabled;
  9745. }
  9746. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9747. Tools.Warn = Tools._WarnEnabled;
  9748. }
  9749. else {
  9750. Tools.Warn = Tools._WarnDisabled;
  9751. }
  9752. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9753. Tools.Error = Tools._ErrorEnabled;
  9754. }
  9755. else {
  9756. Tools.Error = Tools._ErrorDisabled;
  9757. }
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. Tools.IsWindowObjectExist = function () {
  9763. return (typeof window) !== "undefined";
  9764. };
  9765. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9766. get: function () {
  9767. return Tools._PerformanceNoneLogLevel;
  9768. },
  9769. enumerable: true,
  9770. configurable: true
  9771. });
  9772. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9773. get: function () {
  9774. return Tools._PerformanceUserMarkLogLevel;
  9775. },
  9776. enumerable: true,
  9777. configurable: true
  9778. });
  9779. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9780. get: function () {
  9781. return Tools._PerformanceConsoleLogLevel;
  9782. },
  9783. enumerable: true,
  9784. configurable: true
  9785. });
  9786. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9787. set: function (level) {
  9788. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9789. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9790. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9791. return;
  9792. }
  9793. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9794. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9795. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9796. return;
  9797. }
  9798. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9799. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9800. },
  9801. enumerable: true,
  9802. configurable: true
  9803. });
  9804. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9805. };
  9806. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9807. };
  9808. Tools._StartUserMark = function (counterName, condition) {
  9809. if (condition === void 0) { condition = true; }
  9810. if (!Tools._performance) {
  9811. if (!Tools.IsWindowObjectExist()) {
  9812. return;
  9813. }
  9814. Tools._performance = window.performance;
  9815. }
  9816. if (!condition || !Tools._performance.mark) {
  9817. return;
  9818. }
  9819. Tools._performance.mark(counterName + "-Begin");
  9820. };
  9821. Tools._EndUserMark = function (counterName, condition) {
  9822. if (condition === void 0) { condition = true; }
  9823. if (!condition || !Tools._performance.mark) {
  9824. return;
  9825. }
  9826. Tools._performance.mark(counterName + "-End");
  9827. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9828. };
  9829. Tools._StartPerformanceConsole = function (counterName, condition) {
  9830. if (condition === void 0) { condition = true; }
  9831. if (!condition) {
  9832. return;
  9833. }
  9834. Tools._StartUserMark(counterName, condition);
  9835. if (console.time) {
  9836. console.time(counterName);
  9837. }
  9838. };
  9839. Tools._EndPerformanceConsole = function (counterName, condition) {
  9840. if (condition === void 0) { condition = true; }
  9841. if (!condition) {
  9842. return;
  9843. }
  9844. Tools._EndUserMark(counterName, condition);
  9845. if (console.time) {
  9846. console.timeEnd(counterName);
  9847. }
  9848. };
  9849. Object.defineProperty(Tools, "Now", {
  9850. get: function () {
  9851. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9852. return window.performance.now();
  9853. }
  9854. return Date.now();
  9855. },
  9856. enumerable: true,
  9857. configurable: true
  9858. });
  9859. /**
  9860. * This method will return the name of the class used to create the instance of the given object.
  9861. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9862. * @param object the object to get the class name from
  9863. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9864. */
  9865. Tools.GetClassName = function (object, isType) {
  9866. if (isType === void 0) { isType = false; }
  9867. var name = null;
  9868. if (!isType && object.getClassName) {
  9869. name = object.getClassName();
  9870. }
  9871. else {
  9872. if (object instanceof Object) {
  9873. var classObj = isType ? object : Object.getPrototypeOf(object);
  9874. name = classObj.constructor["__bjsclassName__"];
  9875. }
  9876. if (!name) {
  9877. name = typeof object;
  9878. }
  9879. }
  9880. return name;
  9881. };
  9882. Tools.First = function (array, predicate) {
  9883. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9884. var el = array_1[_i];
  9885. if (predicate(el)) {
  9886. return el;
  9887. }
  9888. }
  9889. return null;
  9890. };
  9891. /**
  9892. * This method will return the name of the full name of the class, including its owning module (if any).
  9893. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  9894. * @param object the object to get the class name from
  9895. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  9896. */
  9897. Tools.getFullClassName = function (object, isType) {
  9898. if (isType === void 0) { isType = false; }
  9899. var className = null;
  9900. var moduleName = null;
  9901. if (!isType && object.getClassName) {
  9902. className = object.getClassName();
  9903. }
  9904. else {
  9905. if (object instanceof Object) {
  9906. var classObj = isType ? object : Object.getPrototypeOf(object);
  9907. className = classObj.constructor["__bjsclassName__"];
  9908. moduleName = classObj.constructor["__bjsmoduleName__"];
  9909. }
  9910. if (!className) {
  9911. className = typeof object;
  9912. }
  9913. }
  9914. if (!className) {
  9915. return null;
  9916. }
  9917. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9918. };
  9919. /**
  9920. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9921. * @param array
  9922. */
  9923. Tools.arrayOrStringFeeder = function (array) {
  9924. return function (index) {
  9925. if (index >= array.length) {
  9926. return null;
  9927. }
  9928. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9929. if (val && val.getHashCode) {
  9930. val = val.getHashCode();
  9931. }
  9932. if (typeof val === "string") {
  9933. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9934. }
  9935. return val;
  9936. };
  9937. };
  9938. /**
  9939. * Compute the hashCode of a stream of number
  9940. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9941. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9942. * @return the hash code computed
  9943. */
  9944. Tools.hashCodeFromStream = function (feeder) {
  9945. // Based from here: http://stackoverflow.com/a/7616484/802124
  9946. var hash = 0;
  9947. var index = 0;
  9948. var chr = feeder(index++);
  9949. while (chr != null) {
  9950. hash = ((hash << 5) - hash) + chr;
  9951. hash |= 0; // Convert to 32bit integer
  9952. chr = feeder(index++);
  9953. }
  9954. return hash;
  9955. };
  9956. /**
  9957. * Returns a promise that resolves after the given amount of time.
  9958. * @param delay Number of milliseconds to delay
  9959. * @returns Promise that resolves after the given amount of time
  9960. */
  9961. Tools.DelayAsync = function (delay) {
  9962. return new Promise(function (resolve) {
  9963. setTimeout(function () {
  9964. resolve();
  9965. }, delay);
  9966. });
  9967. };
  9968. /**
  9969. * Gets the current gradient from an array of IValueGradient
  9970. * @param ratio defines the current ratio to get
  9971. * @param gradients defines the array of IValueGradient
  9972. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9973. */
  9974. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9975. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9976. var currentGradient = gradients[gradientIndex];
  9977. var nextGradient = gradients[gradientIndex + 1];
  9978. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9979. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9980. updateFunc(currentGradient, nextGradient, scale);
  9981. }
  9982. }
  9983. };
  9984. Tools.BaseUrl = "";
  9985. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9986. /**
  9987. * Default behaviour for cors in the application.
  9988. * It can be a string if the expected behavior is identical in the entire app.
  9989. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9990. */
  9991. Tools.CorsBehavior = "anonymous";
  9992. Tools.UseFallbackTexture = true;
  9993. /**
  9994. * Use this object to register external classes like custom textures or material
  9995. * to allow the laoders to instantiate them
  9996. */
  9997. Tools.RegisteredExternalClasses = {};
  9998. // Used in case of a texture loading problem
  9999. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  10000. Tools._tmpFloatArray = new Float32Array(1);
  10001. Tools.PreprocessUrl = function (url) {
  10002. return url;
  10003. };
  10004. // Logs
  10005. Tools._NoneLogLevel = 0;
  10006. Tools._MessageLogLevel = 1;
  10007. Tools._WarningLogLevel = 2;
  10008. Tools._ErrorLogLevel = 4;
  10009. Tools._LogCache = "";
  10010. Tools.errorsCount = 0;
  10011. Tools.Log = Tools._LogEnabled;
  10012. Tools.Warn = Tools._WarnEnabled;
  10013. Tools.Error = Tools._ErrorEnabled;
  10014. // Performances
  10015. Tools._PerformanceNoneLogLevel = 0;
  10016. Tools._PerformanceUserMarkLogLevel = 1;
  10017. Tools._PerformanceConsoleLogLevel = 2;
  10018. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10019. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10020. return Tools;
  10021. }());
  10022. BABYLON.Tools = Tools;
  10023. /**
  10024. * This class is used to track a performance counter which is number based.
  10025. * The user has access to many properties which give statistics of different nature
  10026. *
  10027. * The implementer can track two kinds of Performance Counter: time and count
  10028. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  10029. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  10030. */
  10031. var PerfCounter = /** @class */ (function () {
  10032. function PerfCounter() {
  10033. this._startMonitoringTime = 0;
  10034. this._min = 0;
  10035. this._max = 0;
  10036. this._average = 0;
  10037. this._lastSecAverage = 0;
  10038. this._current = 0;
  10039. this._totalValueCount = 0;
  10040. this._totalAccumulated = 0;
  10041. this._lastSecAccumulated = 0;
  10042. this._lastSecTime = 0;
  10043. this._lastSecValueCount = 0;
  10044. }
  10045. Object.defineProperty(PerfCounter.prototype, "min", {
  10046. /**
  10047. * Returns the smallest value ever
  10048. */
  10049. get: function () {
  10050. return this._min;
  10051. },
  10052. enumerable: true,
  10053. configurable: true
  10054. });
  10055. Object.defineProperty(PerfCounter.prototype, "max", {
  10056. /**
  10057. * Returns the biggest value ever
  10058. */
  10059. get: function () {
  10060. return this._max;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(PerfCounter.prototype, "average", {
  10066. /**
  10067. * Returns the average value since the performance counter is running
  10068. */
  10069. get: function () {
  10070. return this._average;
  10071. },
  10072. enumerable: true,
  10073. configurable: true
  10074. });
  10075. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10076. /**
  10077. * Returns the average value of the last second the counter was monitored
  10078. */
  10079. get: function () {
  10080. return this._lastSecAverage;
  10081. },
  10082. enumerable: true,
  10083. configurable: true
  10084. });
  10085. Object.defineProperty(PerfCounter.prototype, "current", {
  10086. /**
  10087. * Returns the current value
  10088. */
  10089. get: function () {
  10090. return this._current;
  10091. },
  10092. enumerable: true,
  10093. configurable: true
  10094. });
  10095. Object.defineProperty(PerfCounter.prototype, "total", {
  10096. get: function () {
  10097. return this._totalAccumulated;
  10098. },
  10099. enumerable: true,
  10100. configurable: true
  10101. });
  10102. Object.defineProperty(PerfCounter.prototype, "count", {
  10103. get: function () {
  10104. return this._totalValueCount;
  10105. },
  10106. enumerable: true,
  10107. configurable: true
  10108. });
  10109. /**
  10110. * Call this method to start monitoring a new frame.
  10111. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  10112. */
  10113. PerfCounter.prototype.fetchNewFrame = function () {
  10114. this._totalValueCount++;
  10115. this._current = 0;
  10116. this._lastSecValueCount++;
  10117. };
  10118. /**
  10119. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10120. * @param newCount the count value to add to the monitored count
  10121. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  10122. */
  10123. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10124. if (!PerfCounter.Enabled) {
  10125. return;
  10126. }
  10127. this._current += newCount;
  10128. if (fetchResult) {
  10129. this._fetchResult();
  10130. }
  10131. };
  10132. /**
  10133. * Start monitoring this performance counter
  10134. */
  10135. PerfCounter.prototype.beginMonitoring = function () {
  10136. if (!PerfCounter.Enabled) {
  10137. return;
  10138. }
  10139. this._startMonitoringTime = Tools.Now;
  10140. };
  10141. /**
  10142. * Compute the time lapsed since the previous beginMonitoring() call.
  10143. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  10144. */
  10145. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10146. if (newFrame === void 0) { newFrame = true; }
  10147. if (!PerfCounter.Enabled) {
  10148. return;
  10149. }
  10150. if (newFrame) {
  10151. this.fetchNewFrame();
  10152. }
  10153. var currentTime = Tools.Now;
  10154. this._current = currentTime - this._startMonitoringTime;
  10155. if (newFrame) {
  10156. this._fetchResult();
  10157. }
  10158. };
  10159. PerfCounter.prototype._fetchResult = function () {
  10160. this._totalAccumulated += this._current;
  10161. this._lastSecAccumulated += this._current;
  10162. // Min/Max update
  10163. this._min = Math.min(this._min, this._current);
  10164. this._max = Math.max(this._max, this._current);
  10165. this._average = this._totalAccumulated / this._totalValueCount;
  10166. // Reset last sec?
  10167. var now = Tools.Now;
  10168. if ((now - this._lastSecTime) > 1000) {
  10169. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10170. this._lastSecTime = now;
  10171. this._lastSecAccumulated = 0;
  10172. this._lastSecValueCount = 0;
  10173. }
  10174. };
  10175. PerfCounter.Enabled = true;
  10176. return PerfCounter;
  10177. }());
  10178. BABYLON.PerfCounter = PerfCounter;
  10179. /**
  10180. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10181. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10182. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10183. * @param name The name of the class, case should be preserved
  10184. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10185. */
  10186. function className(name, module) {
  10187. return function (target) {
  10188. target["__bjsclassName__"] = name;
  10189. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10190. };
  10191. }
  10192. BABYLON.className = className;
  10193. /**
  10194. * An implementation of a loop for asynchronous functions.
  10195. */
  10196. var AsyncLoop = /** @class */ (function () {
  10197. /**
  10198. * Constroctor.
  10199. * @param iterations the number of iterations.
  10200. * @param _fn the function to run each iteration
  10201. * @param _successCallback the callback that will be called upon succesful execution
  10202. * @param offset starting offset.
  10203. */
  10204. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10205. if (offset === void 0) { offset = 0; }
  10206. this.iterations = iterations;
  10207. this._fn = _fn;
  10208. this._successCallback = _successCallback;
  10209. this.index = offset - 1;
  10210. this._done = false;
  10211. }
  10212. /**
  10213. * Execute the next iteration. Must be called after the last iteration was finished.
  10214. */
  10215. AsyncLoop.prototype.executeNext = function () {
  10216. if (!this._done) {
  10217. if (this.index + 1 < this.iterations) {
  10218. ++this.index;
  10219. this._fn(this);
  10220. }
  10221. else {
  10222. this.breakLoop();
  10223. }
  10224. }
  10225. };
  10226. /**
  10227. * Break the loop and run the success callback.
  10228. */
  10229. AsyncLoop.prototype.breakLoop = function () {
  10230. this._done = true;
  10231. this._successCallback();
  10232. };
  10233. /**
  10234. * Helper function
  10235. */
  10236. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10237. if (offset === void 0) { offset = 0; }
  10238. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10239. loop.executeNext();
  10240. return loop;
  10241. };
  10242. /**
  10243. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10244. * @param iterations total number of iterations
  10245. * @param syncedIterations number of synchronous iterations in each async iteration.
  10246. * @param fn the function to call each iteration.
  10247. * @param callback a success call back that will be called when iterating stops.
  10248. * @param breakFunction a break condition (optional)
  10249. * @param timeout timeout settings for the setTimeout function. default - 0.
  10250. * @constructor
  10251. */
  10252. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10253. if (timeout === void 0) { timeout = 0; }
  10254. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10255. if (breakFunction && breakFunction())
  10256. loop.breakLoop();
  10257. else {
  10258. setTimeout(function () {
  10259. for (var i = 0; i < syncedIterations; ++i) {
  10260. var iteration = (loop.index * syncedIterations) + i;
  10261. if (iteration >= iterations)
  10262. break;
  10263. fn(iteration);
  10264. if (breakFunction && breakFunction()) {
  10265. loop.breakLoop();
  10266. break;
  10267. }
  10268. }
  10269. loop.executeNext();
  10270. }, timeout);
  10271. }
  10272. }, callback);
  10273. };
  10274. return AsyncLoop;
  10275. }());
  10276. BABYLON.AsyncLoop = AsyncLoop;
  10277. })(BABYLON || (BABYLON = {}));
  10278. //# sourceMappingURL=babylon.tools.js.map
  10279. var BABYLON;
  10280. (function (BABYLON) {
  10281. var PromiseStates;
  10282. (function (PromiseStates) {
  10283. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10284. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10285. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10286. })(PromiseStates || (PromiseStates = {}));
  10287. var FulFillmentAgregator = /** @class */ (function () {
  10288. function FulFillmentAgregator() {
  10289. this.count = 0;
  10290. this.target = 0;
  10291. this.results = [];
  10292. }
  10293. return FulFillmentAgregator;
  10294. }());
  10295. var InternalPromise = /** @class */ (function () {
  10296. function InternalPromise(resolver) {
  10297. var _this = this;
  10298. this._state = PromiseStates.Pending;
  10299. this._children = new Array();
  10300. this._rejectWasConsumed = false;
  10301. if (!resolver) {
  10302. return;
  10303. }
  10304. try {
  10305. resolver(function (value) {
  10306. _this._resolve(value);
  10307. }, function (reason) {
  10308. _this._reject(reason);
  10309. });
  10310. }
  10311. catch (e) {
  10312. this._reject(e);
  10313. }
  10314. }
  10315. Object.defineProperty(InternalPromise.prototype, "_result", {
  10316. get: function () {
  10317. return this._resultValue;
  10318. },
  10319. set: function (value) {
  10320. this._resultValue = value;
  10321. if (this._parent && this._parent._result === undefined) {
  10322. this._parent._result = value;
  10323. }
  10324. },
  10325. enumerable: true,
  10326. configurable: true
  10327. });
  10328. InternalPromise.prototype.catch = function (onRejected) {
  10329. return this.then(undefined, onRejected);
  10330. };
  10331. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10332. var _this = this;
  10333. var newPromise = new InternalPromise();
  10334. newPromise._onFulfilled = onFulfilled;
  10335. newPromise._onRejected = onRejected;
  10336. // Composition
  10337. this._children.push(newPromise);
  10338. newPromise._parent = this;
  10339. if (this._state !== PromiseStates.Pending) {
  10340. BABYLON.Tools.SetImmediate(function () {
  10341. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10342. var returnedValue = newPromise._resolve(_this._result);
  10343. if (returnedValue !== undefined && returnedValue !== null) {
  10344. if (returnedValue._state !== undefined) {
  10345. var returnedPromise = returnedValue;
  10346. newPromise._children.push(returnedPromise);
  10347. returnedPromise._parent = newPromise;
  10348. newPromise = returnedPromise;
  10349. }
  10350. else {
  10351. newPromise._result = returnedValue;
  10352. }
  10353. }
  10354. }
  10355. else {
  10356. newPromise._reject(_this._reason);
  10357. }
  10358. });
  10359. }
  10360. return newPromise;
  10361. };
  10362. InternalPromise.prototype._moveChildren = function (children) {
  10363. var _this = this;
  10364. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10365. this._children.forEach(function (child) {
  10366. child._parent = _this;
  10367. });
  10368. if (this._state === PromiseStates.Fulfilled) {
  10369. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10370. var child = _b[_i];
  10371. child._resolve(this._result);
  10372. }
  10373. }
  10374. else if (this._state === PromiseStates.Rejected) {
  10375. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10376. var child = _d[_c];
  10377. child._reject(this._reason);
  10378. }
  10379. }
  10380. var _a;
  10381. };
  10382. InternalPromise.prototype._resolve = function (value) {
  10383. try {
  10384. this._state = PromiseStates.Fulfilled;
  10385. var returnedValue = null;
  10386. if (this._onFulfilled) {
  10387. returnedValue = this._onFulfilled(value);
  10388. }
  10389. if (returnedValue !== undefined && returnedValue !== null) {
  10390. if (returnedValue._state !== undefined) {
  10391. // Transmit children
  10392. var returnedPromise = returnedValue;
  10393. returnedPromise._parent = this;
  10394. returnedPromise._moveChildren(this._children);
  10395. value = returnedPromise._result;
  10396. }
  10397. else {
  10398. value = returnedValue;
  10399. }
  10400. }
  10401. this._result = value;
  10402. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10403. var child = _a[_i];
  10404. child._resolve(value);
  10405. }
  10406. this._children.length = 0;
  10407. delete this._onFulfilled;
  10408. delete this._onRejected;
  10409. }
  10410. catch (e) {
  10411. this._reject(e, true);
  10412. }
  10413. };
  10414. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10415. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10416. this._state = PromiseStates.Rejected;
  10417. this._reason = reason;
  10418. if (this._onRejected && !onLocalThrow) {
  10419. try {
  10420. this._onRejected(reason);
  10421. this._rejectWasConsumed = true;
  10422. }
  10423. catch (e) {
  10424. reason = e;
  10425. }
  10426. }
  10427. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10428. var child = _a[_i];
  10429. if (this._rejectWasConsumed) {
  10430. child._resolve(null);
  10431. }
  10432. else {
  10433. child._reject(reason);
  10434. }
  10435. }
  10436. this._children.length = 0;
  10437. delete this._onFulfilled;
  10438. delete this._onRejected;
  10439. };
  10440. InternalPromise.resolve = function (value) {
  10441. var newPromise = new InternalPromise();
  10442. newPromise._resolve(value);
  10443. return newPromise;
  10444. };
  10445. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10446. promise.then(function (value) {
  10447. agregator.results[index] = value;
  10448. agregator.count++;
  10449. if (agregator.count === agregator.target) {
  10450. agregator.rootPromise._resolve(agregator.results);
  10451. }
  10452. return null;
  10453. }, function (reason) {
  10454. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10455. agregator.rootPromise._reject(reason);
  10456. }
  10457. });
  10458. };
  10459. InternalPromise.all = function (promises) {
  10460. var newPromise = new InternalPromise();
  10461. var agregator = new FulFillmentAgregator();
  10462. agregator.target = promises.length;
  10463. agregator.rootPromise = newPromise;
  10464. if (promises.length) {
  10465. for (var index = 0; index < promises.length; index++) {
  10466. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10467. }
  10468. }
  10469. else {
  10470. newPromise._resolve([]);
  10471. }
  10472. return newPromise;
  10473. };
  10474. InternalPromise.race = function (promises) {
  10475. var newPromise = new InternalPromise();
  10476. if (promises.length) {
  10477. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10478. var promise = promises_1[_i];
  10479. promise.then(function (value) {
  10480. if (newPromise) {
  10481. newPromise._resolve(value);
  10482. newPromise = null;
  10483. }
  10484. return null;
  10485. }, function (reason) {
  10486. if (newPromise) {
  10487. newPromise._reject(reason);
  10488. newPromise = null;
  10489. }
  10490. });
  10491. }
  10492. }
  10493. return newPromise;
  10494. };
  10495. return InternalPromise;
  10496. }());
  10497. /**
  10498. * Helper class that provides a small promise polyfill
  10499. */
  10500. var PromisePolyfill = /** @class */ (function () {
  10501. function PromisePolyfill() {
  10502. }
  10503. /**
  10504. * Static function used to check if the polyfill is required
  10505. * If this is the case then the function will inject the polyfill to window.Promise
  10506. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10507. */
  10508. PromisePolyfill.Apply = function (force) {
  10509. if (force === void 0) { force = false; }
  10510. if (force || typeof Promise === 'undefined') {
  10511. var root = window;
  10512. root.Promise = InternalPromise;
  10513. }
  10514. };
  10515. return PromisePolyfill;
  10516. }());
  10517. BABYLON.PromisePolyfill = PromisePolyfill;
  10518. })(BABYLON || (BABYLON = {}));
  10519. //# sourceMappingURL=babylon.promise.js.map
  10520. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10521. var BABYLON;
  10522. (function (BABYLON) {
  10523. /**
  10524. * Helper class to push actions to a pool of workers.
  10525. */
  10526. var WorkerPool = /** @class */ (function () {
  10527. /**
  10528. * Constructor
  10529. * @param workers Array of workers to use for actions
  10530. */
  10531. function WorkerPool(workers) {
  10532. this._pendingActions = new Array();
  10533. this._workerInfos = workers.map(function (worker) { return ({
  10534. worker: worker,
  10535. active: false
  10536. }); });
  10537. }
  10538. /**
  10539. * Terminates all workers and clears any pending actions.
  10540. */
  10541. WorkerPool.prototype.dispose = function () {
  10542. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10543. var workerInfo = _a[_i];
  10544. workerInfo.worker.terminate();
  10545. }
  10546. delete this._workerInfos;
  10547. delete this._pendingActions;
  10548. };
  10549. /**
  10550. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10551. * pended until a worker has completed its action.
  10552. * @param action The action to perform. Call onComplete when the action is complete.
  10553. */
  10554. WorkerPool.prototype.push = function (action) {
  10555. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10556. var workerInfo = _a[_i];
  10557. if (!workerInfo.active) {
  10558. this._execute(workerInfo, action);
  10559. return;
  10560. }
  10561. }
  10562. this._pendingActions.push(action);
  10563. };
  10564. WorkerPool.prototype._execute = function (workerInfo, action) {
  10565. var _this = this;
  10566. workerInfo.active = true;
  10567. action(workerInfo.worker, function () {
  10568. workerInfo.active = false;
  10569. var nextAction = _this._pendingActions.shift();
  10570. if (nextAction) {
  10571. _this._execute(workerInfo, nextAction);
  10572. }
  10573. });
  10574. };
  10575. return WorkerPool;
  10576. }());
  10577. BABYLON.WorkerPool = WorkerPool;
  10578. })(BABYLON || (BABYLON = {}));
  10579. //# sourceMappingURL=babylon.workerPool.js.map
  10580. var BABYLON;
  10581. (function (BABYLON) {
  10582. /**
  10583. * @hidden
  10584. **/
  10585. var _AlphaState = /** @class */ (function () {
  10586. /**
  10587. * Initializes the state.
  10588. */
  10589. function _AlphaState() {
  10590. this._isAlphaBlendDirty = false;
  10591. this._isBlendFunctionParametersDirty = false;
  10592. this._isBlendEquationParametersDirty = false;
  10593. this._isBlendConstantsDirty = false;
  10594. this._alphaBlend = false;
  10595. this._blendFunctionParameters = new Array(4);
  10596. this._blendEquationParameters = new Array(2);
  10597. this._blendConstants = new Array(4);
  10598. this.reset();
  10599. }
  10600. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10601. get: function () {
  10602. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10603. },
  10604. enumerable: true,
  10605. configurable: true
  10606. });
  10607. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10608. get: function () {
  10609. return this._alphaBlend;
  10610. },
  10611. set: function (value) {
  10612. if (this._alphaBlend === value) {
  10613. return;
  10614. }
  10615. this._alphaBlend = value;
  10616. this._isAlphaBlendDirty = true;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10622. if (this._blendConstants[0] === r &&
  10623. this._blendConstants[1] === g &&
  10624. this._blendConstants[2] === b &&
  10625. this._blendConstants[3] === a) {
  10626. return;
  10627. }
  10628. this._blendConstants[0] = r;
  10629. this._blendConstants[1] = g;
  10630. this._blendConstants[2] = b;
  10631. this._blendConstants[3] = a;
  10632. this._isBlendConstantsDirty = true;
  10633. };
  10634. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10635. if (this._blendFunctionParameters[0] === value0 &&
  10636. this._blendFunctionParameters[1] === value1 &&
  10637. this._blendFunctionParameters[2] === value2 &&
  10638. this._blendFunctionParameters[3] === value3) {
  10639. return;
  10640. }
  10641. this._blendFunctionParameters[0] = value0;
  10642. this._blendFunctionParameters[1] = value1;
  10643. this._blendFunctionParameters[2] = value2;
  10644. this._blendFunctionParameters[3] = value3;
  10645. this._isBlendFunctionParametersDirty = true;
  10646. };
  10647. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10648. if (this._blendEquationParameters[0] === rgb &&
  10649. this._blendEquationParameters[1] === alpha) {
  10650. return;
  10651. }
  10652. this._blendEquationParameters[0] = rgb;
  10653. this._blendEquationParameters[1] = alpha;
  10654. this._isBlendEquationParametersDirty = true;
  10655. };
  10656. _AlphaState.prototype.reset = function () {
  10657. this._alphaBlend = false;
  10658. this._blendFunctionParameters[0] = null;
  10659. this._blendFunctionParameters[1] = null;
  10660. this._blendFunctionParameters[2] = null;
  10661. this._blendFunctionParameters[3] = null;
  10662. this._blendEquationParameters[0] = null;
  10663. this._blendEquationParameters[1] = null;
  10664. this._blendConstants[0] = null;
  10665. this._blendConstants[1] = null;
  10666. this._blendConstants[2] = null;
  10667. this._blendConstants[3] = null;
  10668. this._isAlphaBlendDirty = true;
  10669. this._isBlendFunctionParametersDirty = false;
  10670. this._isBlendEquationParametersDirty = false;
  10671. this._isBlendConstantsDirty = false;
  10672. };
  10673. _AlphaState.prototype.apply = function (gl) {
  10674. if (!this.isDirty) {
  10675. return;
  10676. }
  10677. // Alpha blend
  10678. if (this._isAlphaBlendDirty) {
  10679. if (this._alphaBlend) {
  10680. gl.enable(gl.BLEND);
  10681. }
  10682. else {
  10683. gl.disable(gl.BLEND);
  10684. }
  10685. this._isAlphaBlendDirty = false;
  10686. }
  10687. // Alpha function
  10688. if (this._isBlendFunctionParametersDirty) {
  10689. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10690. this._isBlendFunctionParametersDirty = false;
  10691. }
  10692. // Alpha equation
  10693. if (this._isBlendEquationParametersDirty) {
  10694. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10695. this._isBlendEquationParametersDirty = false;
  10696. }
  10697. // Constants
  10698. if (this._isBlendConstantsDirty) {
  10699. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10700. this._isBlendConstantsDirty = false;
  10701. }
  10702. };
  10703. return _AlphaState;
  10704. }());
  10705. BABYLON._AlphaState = _AlphaState;
  10706. })(BABYLON || (BABYLON = {}));
  10707. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10708. var BABYLON;
  10709. (function (BABYLON) {
  10710. /**
  10711. * @hidden
  10712. **/
  10713. var _DepthCullingState = /** @class */ (function () {
  10714. /**
  10715. * Initializes the state.
  10716. */
  10717. function _DepthCullingState() {
  10718. this._isDepthTestDirty = false;
  10719. this._isDepthMaskDirty = false;
  10720. this._isDepthFuncDirty = false;
  10721. this._isCullFaceDirty = false;
  10722. this._isCullDirty = false;
  10723. this._isZOffsetDirty = false;
  10724. this._isFrontFaceDirty = false;
  10725. this.reset();
  10726. }
  10727. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10728. get: function () {
  10729. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10735. get: function () {
  10736. return this._zOffset;
  10737. },
  10738. set: function (value) {
  10739. if (this._zOffset === value) {
  10740. return;
  10741. }
  10742. this._zOffset = value;
  10743. this._isZOffsetDirty = true;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10749. get: function () {
  10750. return this._cullFace;
  10751. },
  10752. set: function (value) {
  10753. if (this._cullFace === value) {
  10754. return;
  10755. }
  10756. this._cullFace = value;
  10757. this._isCullFaceDirty = true;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10763. get: function () {
  10764. return this._cull;
  10765. },
  10766. set: function (value) {
  10767. if (this._cull === value) {
  10768. return;
  10769. }
  10770. this._cull = value;
  10771. this._isCullDirty = true;
  10772. },
  10773. enumerable: true,
  10774. configurable: true
  10775. });
  10776. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10777. get: function () {
  10778. return this._depthFunc;
  10779. },
  10780. set: function (value) {
  10781. if (this._depthFunc === value) {
  10782. return;
  10783. }
  10784. this._depthFunc = value;
  10785. this._isDepthFuncDirty = true;
  10786. },
  10787. enumerable: true,
  10788. configurable: true
  10789. });
  10790. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10791. get: function () {
  10792. return this._depthMask;
  10793. },
  10794. set: function (value) {
  10795. if (this._depthMask === value) {
  10796. return;
  10797. }
  10798. this._depthMask = value;
  10799. this._isDepthMaskDirty = true;
  10800. },
  10801. enumerable: true,
  10802. configurable: true
  10803. });
  10804. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10805. get: function () {
  10806. return this._depthTest;
  10807. },
  10808. set: function (value) {
  10809. if (this._depthTest === value) {
  10810. return;
  10811. }
  10812. this._depthTest = value;
  10813. this._isDepthTestDirty = true;
  10814. },
  10815. enumerable: true,
  10816. configurable: true
  10817. });
  10818. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10819. get: function () {
  10820. return this._frontFace;
  10821. },
  10822. set: function (value) {
  10823. if (this._frontFace === value) {
  10824. return;
  10825. }
  10826. this._frontFace = value;
  10827. this._isFrontFaceDirty = true;
  10828. },
  10829. enumerable: true,
  10830. configurable: true
  10831. });
  10832. _DepthCullingState.prototype.reset = function () {
  10833. this._depthMask = true;
  10834. this._depthTest = true;
  10835. this._depthFunc = null;
  10836. this._cullFace = null;
  10837. this._cull = null;
  10838. this._zOffset = 0;
  10839. this._frontFace = null;
  10840. this._isDepthTestDirty = true;
  10841. this._isDepthMaskDirty = true;
  10842. this._isDepthFuncDirty = false;
  10843. this._isCullFaceDirty = false;
  10844. this._isCullDirty = false;
  10845. this._isZOffsetDirty = false;
  10846. this._isFrontFaceDirty = false;
  10847. };
  10848. _DepthCullingState.prototype.apply = function (gl) {
  10849. if (!this.isDirty) {
  10850. return;
  10851. }
  10852. // Cull
  10853. if (this._isCullDirty) {
  10854. if (this.cull) {
  10855. gl.enable(gl.CULL_FACE);
  10856. }
  10857. else {
  10858. gl.disable(gl.CULL_FACE);
  10859. }
  10860. this._isCullDirty = false;
  10861. }
  10862. // Cull face
  10863. if (this._isCullFaceDirty) {
  10864. gl.cullFace(this.cullFace);
  10865. this._isCullFaceDirty = false;
  10866. }
  10867. // Depth mask
  10868. if (this._isDepthMaskDirty) {
  10869. gl.depthMask(this.depthMask);
  10870. this._isDepthMaskDirty = false;
  10871. }
  10872. // Depth test
  10873. if (this._isDepthTestDirty) {
  10874. if (this.depthTest) {
  10875. gl.enable(gl.DEPTH_TEST);
  10876. }
  10877. else {
  10878. gl.disable(gl.DEPTH_TEST);
  10879. }
  10880. this._isDepthTestDirty = false;
  10881. }
  10882. // Depth func
  10883. if (this._isDepthFuncDirty) {
  10884. gl.depthFunc(this.depthFunc);
  10885. this._isDepthFuncDirty = false;
  10886. }
  10887. // zOffset
  10888. if (this._isZOffsetDirty) {
  10889. if (this.zOffset) {
  10890. gl.enable(gl.POLYGON_OFFSET_FILL);
  10891. gl.polygonOffset(this.zOffset, 0);
  10892. }
  10893. else {
  10894. gl.disable(gl.POLYGON_OFFSET_FILL);
  10895. }
  10896. this._isZOffsetDirty = false;
  10897. }
  10898. // Front face
  10899. if (this._isFrontFaceDirty) {
  10900. gl.frontFace(this.frontFace);
  10901. this._isFrontFaceDirty = false;
  10902. }
  10903. };
  10904. return _DepthCullingState;
  10905. }());
  10906. BABYLON._DepthCullingState = _DepthCullingState;
  10907. })(BABYLON || (BABYLON = {}));
  10908. //# sourceMappingURL=babylon.depthCullingState.js.map
  10909. var BABYLON;
  10910. (function (BABYLON) {
  10911. /**
  10912. * @hidden
  10913. **/
  10914. var _StencilState = /** @class */ (function () {
  10915. function _StencilState() {
  10916. this._isStencilTestDirty = false;
  10917. this._isStencilMaskDirty = false;
  10918. this._isStencilFuncDirty = false;
  10919. this._isStencilOpDirty = false;
  10920. this.reset();
  10921. }
  10922. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10923. get: function () {
  10924. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10930. get: function () {
  10931. return this._stencilFunc;
  10932. },
  10933. set: function (value) {
  10934. if (this._stencilFunc === value) {
  10935. return;
  10936. }
  10937. this._stencilFunc = value;
  10938. this._isStencilFuncDirty = true;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10944. get: function () {
  10945. return this._stencilFuncRef;
  10946. },
  10947. set: function (value) {
  10948. if (this._stencilFuncRef === value) {
  10949. return;
  10950. }
  10951. this._stencilFuncRef = value;
  10952. this._isStencilFuncDirty = true;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10958. get: function () {
  10959. return this._stencilFuncMask;
  10960. },
  10961. set: function (value) {
  10962. if (this._stencilFuncMask === value) {
  10963. return;
  10964. }
  10965. this._stencilFuncMask = value;
  10966. this._isStencilFuncDirty = true;
  10967. },
  10968. enumerable: true,
  10969. configurable: true
  10970. });
  10971. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10972. get: function () {
  10973. return this._stencilOpStencilFail;
  10974. },
  10975. set: function (value) {
  10976. if (this._stencilOpStencilFail === value) {
  10977. return;
  10978. }
  10979. this._stencilOpStencilFail = value;
  10980. this._isStencilOpDirty = true;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10986. get: function () {
  10987. return this._stencilOpDepthFail;
  10988. },
  10989. set: function (value) {
  10990. if (this._stencilOpDepthFail === value) {
  10991. return;
  10992. }
  10993. this._stencilOpDepthFail = value;
  10994. this._isStencilOpDirty = true;
  10995. },
  10996. enumerable: true,
  10997. configurable: true
  10998. });
  10999. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11000. get: function () {
  11001. return this._stencilOpStencilDepthPass;
  11002. },
  11003. set: function (value) {
  11004. if (this._stencilOpStencilDepthPass === value) {
  11005. return;
  11006. }
  11007. this._stencilOpStencilDepthPass = value;
  11008. this._isStencilOpDirty = true;
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11014. get: function () {
  11015. return this._stencilMask;
  11016. },
  11017. set: function (value) {
  11018. if (this._stencilMask === value) {
  11019. return;
  11020. }
  11021. this._stencilMask = value;
  11022. this._isStencilMaskDirty = true;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11028. get: function () {
  11029. return this._stencilTest;
  11030. },
  11031. set: function (value) {
  11032. if (this._stencilTest === value) {
  11033. return;
  11034. }
  11035. this._stencilTest = value;
  11036. this._isStencilTestDirty = true;
  11037. },
  11038. enumerable: true,
  11039. configurable: true
  11040. });
  11041. _StencilState.prototype.reset = function () {
  11042. this._stencilTest = false;
  11043. this._stencilMask = 0xFF;
  11044. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11045. this._stencilFuncRef = 1;
  11046. this._stencilFuncMask = 0xFF;
  11047. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11048. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11049. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11050. this._isStencilTestDirty = true;
  11051. this._isStencilMaskDirty = true;
  11052. this._isStencilFuncDirty = true;
  11053. this._isStencilOpDirty = true;
  11054. };
  11055. _StencilState.prototype.apply = function (gl) {
  11056. if (!this.isDirty) {
  11057. return;
  11058. }
  11059. // Stencil test
  11060. if (this._isStencilTestDirty) {
  11061. if (this.stencilTest) {
  11062. gl.enable(gl.STENCIL_TEST);
  11063. }
  11064. else {
  11065. gl.disable(gl.STENCIL_TEST);
  11066. }
  11067. this._isStencilTestDirty = false;
  11068. }
  11069. // Stencil mask
  11070. if (this._isStencilMaskDirty) {
  11071. gl.stencilMask(this.stencilMask);
  11072. this._isStencilMaskDirty = false;
  11073. }
  11074. // Stencil func
  11075. if (this._isStencilFuncDirty) {
  11076. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11077. this._isStencilFuncDirty = false;
  11078. }
  11079. // Stencil op
  11080. if (this._isStencilOpDirty) {
  11081. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11082. this._isStencilOpDirty = false;
  11083. }
  11084. };
  11085. return _StencilState;
  11086. }());
  11087. BABYLON._StencilState = _StencilState;
  11088. })(BABYLON || (BABYLON = {}));
  11089. //# sourceMappingURL=babylon.stencilState.js.map
  11090. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11091. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11092. s = arguments[i];
  11093. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11094. t[p] = s[p];
  11095. }
  11096. return t;
  11097. };
  11098. var BABYLON;
  11099. (function (BABYLON) {
  11100. /**
  11101. * Keeps track of all the buffer info used in engine.
  11102. */
  11103. var BufferPointer = /** @class */ (function () {
  11104. function BufferPointer() {
  11105. }
  11106. return BufferPointer;
  11107. }());
  11108. /**
  11109. * Interface for attribute information associated with buffer instanciation
  11110. */
  11111. var InstancingAttributeInfo = /** @class */ (function () {
  11112. function InstancingAttributeInfo() {
  11113. }
  11114. return InstancingAttributeInfo;
  11115. }());
  11116. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11117. /**
  11118. * Define options used to create a render target texture
  11119. */
  11120. var RenderTargetCreationOptions = /** @class */ (function () {
  11121. function RenderTargetCreationOptions() {
  11122. }
  11123. return RenderTargetCreationOptions;
  11124. }());
  11125. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11126. /**
  11127. * Define options used to create a depth texture
  11128. */
  11129. var DepthTextureCreationOptions = /** @class */ (function () {
  11130. function DepthTextureCreationOptions() {
  11131. }
  11132. return DepthTextureCreationOptions;
  11133. }());
  11134. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11135. /**
  11136. * Class used to describe the capabilities of the engine relatively to the current browser
  11137. */
  11138. var EngineCapabilities = /** @class */ (function () {
  11139. function EngineCapabilities() {
  11140. }
  11141. return EngineCapabilities;
  11142. }());
  11143. BABYLON.EngineCapabilities = EngineCapabilities;
  11144. /**
  11145. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11146. */
  11147. var Engine = /** @class */ (function () {
  11148. /**
  11149. * Creates a new engine
  11150. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11151. * @param antialias defines enable antialiasing (default: false)
  11152. * @param options defines further options to be sent to the getContext() function
  11153. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11154. */
  11155. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11156. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11157. var _this = this;
  11158. // Public members
  11159. /**
  11160. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11161. */
  11162. this.forcePOTTextures = false;
  11163. /**
  11164. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11165. */
  11166. this.isFullscreen = false;
  11167. /**
  11168. * Gets a boolean indicating if the pointer is currently locked
  11169. */
  11170. this.isPointerLock = false;
  11171. /**
  11172. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11173. */
  11174. this.cullBackFaces = true;
  11175. /**
  11176. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11177. */
  11178. this.renderEvenInBackground = true;
  11179. /**
  11180. * Gets or sets a boolean indicating that cache can be kept between frames
  11181. */
  11182. this.preventCacheWipeBetweenFrames = false;
  11183. /**
  11184. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11185. **/
  11186. this.enableOfflineSupport = false;
  11187. /**
  11188. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11189. **/
  11190. this.disableManifestCheck = false;
  11191. /**
  11192. * Gets the list of created scenes
  11193. */
  11194. this.scenes = new Array();
  11195. /**
  11196. * Gets the list of created postprocesses
  11197. */
  11198. this.postProcesses = new Array();
  11199. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11200. this.validateShaderPrograms = false;
  11201. // Observables
  11202. /**
  11203. * Observable event triggered each time the rendering canvas is resized
  11204. */
  11205. this.onResizeObservable = new BABYLON.Observable();
  11206. /**
  11207. * Observable event triggered each time the canvas loses focus
  11208. */
  11209. this.onCanvasBlurObservable = new BABYLON.Observable();
  11210. /**
  11211. * Observable event triggered each time the canvas gains focus
  11212. */
  11213. this.onCanvasFocusObservable = new BABYLON.Observable();
  11214. /**
  11215. * Observable event triggered each time the canvas receives pointerout event
  11216. */
  11217. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11218. /**
  11219. * Observable event triggered before each texture is initialized
  11220. */
  11221. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11222. //WebVR
  11223. this._vrDisplay = undefined;
  11224. this._vrSupported = false;
  11225. this._vrExclusivePointerMode = false;
  11226. // Uniform buffers list
  11227. /**
  11228. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11229. */
  11230. this.disableUniformBuffers = false;
  11231. /** @hidden */
  11232. this._uniformBuffers = new Array();
  11233. // Observables
  11234. /**
  11235. * Observable raised when the engine begins a new frame
  11236. */
  11237. this.onBeginFrameObservable = new BABYLON.Observable();
  11238. /**
  11239. * Observable raised when the engine ends the current frame
  11240. */
  11241. this.onEndFrameObservable = new BABYLON.Observable();
  11242. /**
  11243. * Observable raised when the engine is about to compile a shader
  11244. */
  11245. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11246. /**
  11247. * Observable raised when the engine has jsut compiled a shader
  11248. */
  11249. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11250. this._windowIsBackground = false;
  11251. this._webGLVersion = 1.0;
  11252. /** @hidden */
  11253. this._badOS = false;
  11254. /** @hidden */
  11255. this._badDesktopOS = false;
  11256. /**
  11257. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11258. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11259. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11260. */
  11261. this.disableTextureBindingOptimization = false;
  11262. /**
  11263. * Observable signaled when VR display mode changes
  11264. */
  11265. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11266. /**
  11267. * Observable signaled when VR request present is complete
  11268. */
  11269. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11270. /**
  11271. * Observable signaled when VR request present starts
  11272. */
  11273. this.onVRRequestPresentStart = new BABYLON.Observable();
  11274. this._colorWrite = true;
  11275. /** @hidden */
  11276. this._drawCalls = new BABYLON.PerfCounter();
  11277. /** @hidden */
  11278. this._textureCollisions = new BABYLON.PerfCounter();
  11279. this._renderingQueueLaunched = false;
  11280. this._activeRenderLoops = new Array();
  11281. // Deterministic lockstepMaxSteps
  11282. this._deterministicLockstep = false;
  11283. this._lockstepMaxSteps = 4;
  11284. // Lost context
  11285. /**
  11286. * Observable signaled when a context lost event is raised
  11287. */
  11288. this.onContextLostObservable = new BABYLON.Observable();
  11289. /**
  11290. * Observable signaled when a context restored event is raised
  11291. */
  11292. this.onContextRestoredObservable = new BABYLON.Observable();
  11293. this._contextWasLost = false;
  11294. this._doNotHandleContextLost = false;
  11295. // FPS
  11296. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11297. this._fps = 60;
  11298. this._deltaTime = 0;
  11299. /**
  11300. * Turn this value on if you want to pause FPS computation when in background
  11301. */
  11302. this.disablePerformanceMonitorInBackground = false;
  11303. // States
  11304. /** @hidden */
  11305. this._depthCullingState = new BABYLON._DepthCullingState();
  11306. /** @hidden */
  11307. this._stencilState = new BABYLON._StencilState();
  11308. /** @hidden */
  11309. this._alphaState = new BABYLON._AlphaState();
  11310. /** @hidden */
  11311. this._alphaMode = Engine.ALPHA_DISABLE;
  11312. // Cache
  11313. this._internalTexturesCache = new Array();
  11314. /** @hidden */
  11315. this._activeChannel = 0;
  11316. this._currentTextureChannel = -1;
  11317. /** @hidden */
  11318. this._boundTexturesCache = {};
  11319. this._compiledEffects = {};
  11320. this._vertexAttribArraysEnabled = [];
  11321. this._uintIndicesCurrentlySet = false;
  11322. this._currentBoundBuffer = new Array();
  11323. /** @hidden */
  11324. this._currentFramebuffer = null;
  11325. this._currentBufferPointers = new Array();
  11326. this._currentInstanceLocations = new Array();
  11327. this._currentInstanceBuffers = new Array();
  11328. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11329. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11330. this._vaoRecordInProgress = false;
  11331. this._mustWipeVertexAttributes = false;
  11332. this._nextFreeTextureSlots = new Array();
  11333. this._maxSimultaneousTextures = 0;
  11334. this._activeRequests = new Array();
  11335. // Hardware supported Compressed Textures
  11336. this._texturesSupported = new Array();
  11337. /**
  11338. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11339. */
  11340. this.premultipliedAlpha = true;
  11341. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11342. this._onVRFullScreenTriggered = function () {
  11343. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11344. //get the old size before we change
  11345. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11346. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11347. //get the width and height, change the render size
  11348. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11349. _this.setHardwareScalingLevel(1);
  11350. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11351. }
  11352. else {
  11353. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11354. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11355. }
  11356. };
  11357. this._unpackFlipYCached = null;
  11358. this._boundUniforms = {};
  11359. // Register promises
  11360. BABYLON.PromisePolyfill.Apply();
  11361. var canvas = null;
  11362. Engine.Instances.push(this);
  11363. if (!canvasOrContext) {
  11364. return;
  11365. }
  11366. options = options || {};
  11367. if (canvasOrContext.getContext) {
  11368. canvas = canvasOrContext;
  11369. this._renderingCanvas = canvas;
  11370. if (antialias != null) {
  11371. options.antialias = antialias;
  11372. }
  11373. if (options.deterministicLockstep === undefined) {
  11374. options.deterministicLockstep = false;
  11375. }
  11376. if (options.lockstepMaxSteps === undefined) {
  11377. options.lockstepMaxSteps = 4;
  11378. }
  11379. if (options.preserveDrawingBuffer === undefined) {
  11380. options.preserveDrawingBuffer = false;
  11381. }
  11382. if (options.audioEngine === undefined) {
  11383. options.audioEngine = true;
  11384. }
  11385. if (options.stencil === undefined) {
  11386. options.stencil = true;
  11387. }
  11388. if (options.premultipliedAlpha === false) {
  11389. this.premultipliedAlpha = false;
  11390. }
  11391. this._deterministicLockstep = options.deterministicLockstep;
  11392. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11393. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11394. // Exceptions
  11395. if (navigator && navigator.userAgent) {
  11396. var ua = navigator.userAgent;
  11397. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11398. var exception = _a[_i];
  11399. var key = exception.key;
  11400. var targets = exception.targets;
  11401. if (ua.indexOf(key) > -1) {
  11402. if (exception.capture && exception.captureConstraint) {
  11403. var capture = exception.capture;
  11404. var constraint = exception.captureConstraint;
  11405. var regex = new RegExp(capture);
  11406. var matches = regex.exec(ua);
  11407. if (matches && matches.length > 0) {
  11408. var capturedValue = parseInt(matches[matches.length - 1]);
  11409. if (capturedValue >= constraint) {
  11410. continue;
  11411. }
  11412. }
  11413. }
  11414. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11415. var target = targets_1[_b];
  11416. switch (target) {
  11417. case "uniformBuffer":
  11418. this.disableUniformBuffers = true;
  11419. break;
  11420. case "textureBindingOptimization":
  11421. this.disableTextureBindingOptimization = true;
  11422. break;
  11423. }
  11424. }
  11425. }
  11426. }
  11427. }
  11428. // GL
  11429. if (!options.disableWebGL2Support) {
  11430. try {
  11431. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11432. if (this._gl) {
  11433. this._webGLVersion = 2.0;
  11434. }
  11435. }
  11436. catch (e) {
  11437. // Do nothing
  11438. }
  11439. }
  11440. if (!this._gl) {
  11441. if (!canvas) {
  11442. throw new Error("The provided canvas is null or undefined.");
  11443. }
  11444. try {
  11445. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11446. }
  11447. catch (e) {
  11448. throw new Error("WebGL not supported");
  11449. }
  11450. }
  11451. if (!this._gl) {
  11452. throw new Error("WebGL not supported");
  11453. }
  11454. this._onCanvasFocus = function () {
  11455. _this.onCanvasFocusObservable.notifyObservers(_this);
  11456. };
  11457. this._onCanvasBlur = function () {
  11458. _this.onCanvasBlurObservable.notifyObservers(_this);
  11459. };
  11460. canvas.addEventListener("focus", this._onCanvasFocus);
  11461. canvas.addEventListener("blur", this._onCanvasBlur);
  11462. this._onBlur = function () {
  11463. if (_this.disablePerformanceMonitorInBackground) {
  11464. _this._performanceMonitor.disable();
  11465. }
  11466. _this._windowIsBackground = true;
  11467. };
  11468. this._onFocus = function () {
  11469. if (_this.disablePerformanceMonitorInBackground) {
  11470. _this._performanceMonitor.enable();
  11471. }
  11472. _this._windowIsBackground = false;
  11473. };
  11474. this._onCanvasPointerOut = function (ev) {
  11475. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11476. };
  11477. window.addEventListener("blur", this._onBlur);
  11478. window.addEventListener("focus", this._onFocus);
  11479. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11480. // Context lost
  11481. if (!this._doNotHandleContextLost) {
  11482. this._onContextLost = function (evt) {
  11483. evt.preventDefault();
  11484. _this._contextWasLost = true;
  11485. BABYLON.Tools.Warn("WebGL context lost.");
  11486. _this.onContextLostObservable.notifyObservers(_this);
  11487. };
  11488. this._onContextRestored = function (evt) {
  11489. // Adding a timeout to avoid race condition at browser level
  11490. setTimeout(function () {
  11491. // Rebuild gl context
  11492. _this._initGLContext();
  11493. // Rebuild effects
  11494. _this._rebuildEffects();
  11495. // Rebuild textures
  11496. _this._rebuildInternalTextures();
  11497. // Rebuild buffers
  11498. _this._rebuildBuffers();
  11499. // Cache
  11500. _this.wipeCaches(true);
  11501. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11502. _this.onContextRestoredObservable.notifyObservers(_this);
  11503. _this._contextWasLost = false;
  11504. }, 0);
  11505. };
  11506. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11507. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11508. }
  11509. }
  11510. else {
  11511. this._gl = canvasOrContext;
  11512. this._renderingCanvas = this._gl.canvas;
  11513. if (this._gl.renderbufferStorageMultisample) {
  11514. this._webGLVersion = 2.0;
  11515. }
  11516. options.stencil = this._gl.getContextAttributes().stencil;
  11517. }
  11518. // Viewport
  11519. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11520. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11521. this.resize();
  11522. this._isStencilEnable = options.stencil ? true : false;
  11523. this._initGLContext();
  11524. if (canvas) {
  11525. // Fullscreen
  11526. this._onFullscreenChange = function () {
  11527. if (document.fullscreen !== undefined) {
  11528. _this.isFullscreen = document.fullscreen;
  11529. }
  11530. else if (document.mozFullScreen !== undefined) {
  11531. _this.isFullscreen = document.mozFullScreen;
  11532. }
  11533. else if (document.webkitIsFullScreen !== undefined) {
  11534. _this.isFullscreen = document.webkitIsFullScreen;
  11535. }
  11536. else if (document.msIsFullScreen !== undefined) {
  11537. _this.isFullscreen = document.msIsFullScreen;
  11538. }
  11539. // Pointer lock
  11540. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11541. canvas.requestPointerLock = canvas.requestPointerLock ||
  11542. canvas.msRequestPointerLock ||
  11543. canvas.mozRequestPointerLock ||
  11544. canvas.webkitRequestPointerLock;
  11545. if (canvas.requestPointerLock) {
  11546. canvas.requestPointerLock();
  11547. }
  11548. }
  11549. };
  11550. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11551. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11552. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11553. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11554. // Pointer lock
  11555. this._onPointerLockChange = function () {
  11556. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11557. document.webkitPointerLockElement === canvas ||
  11558. document.msPointerLockElement === canvas ||
  11559. document.pointerLockElement === canvas);
  11560. };
  11561. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11562. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11563. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11564. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11565. this._onVRDisplayPointerRestricted = function () {
  11566. if (canvas) {
  11567. canvas.requestPointerLock();
  11568. }
  11569. };
  11570. this._onVRDisplayPointerUnrestricted = function () {
  11571. document.exitPointerLock();
  11572. };
  11573. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11574. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11575. }
  11576. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11577. Engine.audioEngine = new BABYLON.AudioEngine();
  11578. }
  11579. // Prepare buffer pointers
  11580. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11581. this._currentBufferPointers[i] = new BufferPointer();
  11582. }
  11583. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11584. // Load WebVR Devices
  11585. if (options.autoEnableWebVR) {
  11586. this.initWebVR();
  11587. }
  11588. // Detect if we are running on a faulty buggy OS.
  11589. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11590. // Detect if we are running on a faulty buggy desktop OS.
  11591. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11592. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11593. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11594. }
  11595. Object.defineProperty(Engine, "LastCreatedEngine", {
  11596. /**
  11597. * Gets the latest created engine
  11598. */
  11599. get: function () {
  11600. if (Engine.Instances.length === 0) {
  11601. return null;
  11602. }
  11603. return Engine.Instances[Engine.Instances.length - 1];
  11604. },
  11605. enumerable: true,
  11606. configurable: true
  11607. });
  11608. Object.defineProperty(Engine, "LastCreatedScene", {
  11609. /**
  11610. * Gets the latest created scene
  11611. */
  11612. get: function () {
  11613. var lastCreatedEngine = Engine.LastCreatedEngine;
  11614. if (!lastCreatedEngine) {
  11615. return null;
  11616. }
  11617. if (lastCreatedEngine.scenes.length === 0) {
  11618. return null;
  11619. }
  11620. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11621. },
  11622. enumerable: true,
  11623. configurable: true
  11624. });
  11625. /**
  11626. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11627. * @param flag defines which part of the materials must be marked as dirty
  11628. * @param predicate defines a predicate used to filter which materials should be affected
  11629. */
  11630. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11631. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11632. var engine = Engine.Instances[engineIndex];
  11633. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11634. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11635. }
  11636. }
  11637. };
  11638. Object.defineProperty(Engine, "Version", {
  11639. /**
  11640. * Returns the current version of the framework
  11641. */
  11642. get: function () {
  11643. return "3.3.0-alpha.12";
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11649. /**
  11650. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11651. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11652. */
  11653. get: function () {
  11654. return this._vrExclusivePointerMode;
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11660. /**
  11661. * Gets a boolean indicating that the engine supports uniform buffers
  11662. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11663. */
  11664. get: function () {
  11665. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11666. },
  11667. enumerable: true,
  11668. configurable: true
  11669. });
  11670. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11671. /**
  11672. * Gets a boolean indicating that only power of 2 textures are supported
  11673. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11674. */
  11675. get: function () {
  11676. return this._webGLVersion < 2 || this.forcePOTTextures;
  11677. },
  11678. enumerable: true,
  11679. configurable: true
  11680. });
  11681. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11682. /**
  11683. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11684. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11685. */
  11686. get: function () {
  11687. return this._doNotHandleContextLost;
  11688. },
  11689. set: function (value) {
  11690. this._doNotHandleContextLost = value;
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11696. /**
  11697. * Gets the performance monitor attached to this engine
  11698. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11699. */
  11700. get: function () {
  11701. return this._performanceMonitor;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11707. /**
  11708. * Gets the list of texture formats supported
  11709. */
  11710. get: function () {
  11711. return this._texturesSupported;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11717. /**
  11718. * Gets the list of texture formats in use
  11719. */
  11720. get: function () {
  11721. return this._textureFormatInUse;
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Engine.prototype, "currentViewport", {
  11727. /**
  11728. * Gets the current viewport
  11729. */
  11730. get: function () {
  11731. return this._cachedViewport;
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11737. /**
  11738. * Gets the default empty texture
  11739. */
  11740. get: function () {
  11741. if (!this._emptyTexture) {
  11742. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11743. }
  11744. return this._emptyTexture;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11750. /**
  11751. * Gets the default empty 3D texture
  11752. */
  11753. get: function () {
  11754. if (!this._emptyTexture3D) {
  11755. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11756. }
  11757. return this._emptyTexture3D;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11763. /**
  11764. * Gets the default empty cube texture
  11765. */
  11766. get: function () {
  11767. if (!this._emptyCubeTexture) {
  11768. var faceData = new Uint8Array(4);
  11769. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11770. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11771. }
  11772. return this._emptyCubeTexture;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Engine.prototype._rebuildInternalTextures = function () {
  11778. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11779. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11780. var internalTexture = currentState_1[_i];
  11781. internalTexture._rebuild();
  11782. }
  11783. };
  11784. Engine.prototype._rebuildEffects = function () {
  11785. for (var key in this._compiledEffects) {
  11786. var effect = this._compiledEffects[key];
  11787. effect._prepareEffect();
  11788. }
  11789. BABYLON.Effect.ResetCache();
  11790. };
  11791. Engine.prototype._rebuildBuffers = function () {
  11792. // Index / Vertex
  11793. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11794. var scene = _a[_i];
  11795. scene.resetCachedMaterial();
  11796. scene._rebuildGeometries();
  11797. scene._rebuildTextures();
  11798. }
  11799. // Uniforms
  11800. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11801. var uniformBuffer = _c[_b];
  11802. uniformBuffer._rebuild();
  11803. }
  11804. };
  11805. Engine.prototype._initGLContext = function () {
  11806. // Caps
  11807. this._caps = new EngineCapabilities();
  11808. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11809. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11810. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11811. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11812. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11813. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11814. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11815. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11816. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11817. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11818. // Infos
  11819. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11820. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11821. if (rendererInfo != null) {
  11822. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11823. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11824. }
  11825. if (!this._glVendor) {
  11826. this._glVendor = "Unknown vendor";
  11827. }
  11828. if (!this._glRenderer) {
  11829. this._glRenderer = "Unknown renderer";
  11830. }
  11831. // Constants
  11832. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11833. if (this._gl.RGBA16F !== 0x881A) {
  11834. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11835. }
  11836. if (this._gl.RGBA32F !== 0x8814) {
  11837. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11838. }
  11839. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11840. this._gl.DEPTH24_STENCIL8 = 35056;
  11841. }
  11842. // Extensions
  11843. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11844. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11845. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11846. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11847. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11848. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11849. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11850. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  11851. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11852. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11853. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11854. this._caps.highPrecisionShaderSupported = true;
  11855. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11856. if (this._caps.timerQuery) {
  11857. if (this._webGLVersion === 1) {
  11858. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11859. }
  11860. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11861. }
  11862. // Checks if some of the format renders first to allow the use of webgl inspector.
  11863. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11864. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11865. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11866. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11867. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11868. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11869. if (this._webGLVersion > 1) {
  11870. this._gl.HALF_FLOAT_OES = 0x140B;
  11871. }
  11872. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11873. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11874. // Draw buffers
  11875. if (this._webGLVersion > 1) {
  11876. this._caps.drawBuffersExtension = true;
  11877. }
  11878. else {
  11879. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11880. if (drawBuffersExtension !== null) {
  11881. this._caps.drawBuffersExtension = true;
  11882. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11883. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11884. for (var i = 0; i < 16; i++) {
  11885. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11886. }
  11887. }
  11888. else {
  11889. this._caps.drawBuffersExtension = false;
  11890. }
  11891. }
  11892. // Depth Texture
  11893. if (this._webGLVersion > 1) {
  11894. this._caps.depthTextureExtension = true;
  11895. }
  11896. else {
  11897. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11898. if (depthTextureExtension != null) {
  11899. this._caps.depthTextureExtension = true;
  11900. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11901. }
  11902. }
  11903. // Vertex array object
  11904. if (this._webGLVersion > 1) {
  11905. this._caps.vertexArrayObject = true;
  11906. }
  11907. else {
  11908. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11909. if (vertexArrayObjectExtension != null) {
  11910. this._caps.vertexArrayObject = true;
  11911. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11912. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11913. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11914. }
  11915. else {
  11916. this._caps.vertexArrayObject = false;
  11917. }
  11918. }
  11919. // Instances count
  11920. if (this._webGLVersion > 1) {
  11921. this._caps.instancedArrays = true;
  11922. }
  11923. else {
  11924. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11925. if (instanceExtension != null) {
  11926. this._caps.instancedArrays = true;
  11927. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11928. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11929. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11930. }
  11931. else {
  11932. this._caps.instancedArrays = false;
  11933. }
  11934. }
  11935. // Intelligently add supported compressed formats in order to check for.
  11936. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11937. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11938. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11939. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11940. if (this._caps.astc)
  11941. this.texturesSupported.push('-astc.ktx');
  11942. if (this._caps.s3tc)
  11943. this.texturesSupported.push('-dxt.ktx');
  11944. if (this._caps.pvrtc)
  11945. this.texturesSupported.push('-pvrtc.ktx');
  11946. if (this._caps.etc2)
  11947. this.texturesSupported.push('-etc2.ktx');
  11948. if (this._caps.etc1)
  11949. this.texturesSupported.push('-etc1.ktx');
  11950. if (this._gl.getShaderPrecisionFormat) {
  11951. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11952. if (highp) {
  11953. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11954. }
  11955. }
  11956. // Depth buffer
  11957. this.setDepthBuffer(true);
  11958. this.setDepthFunctionToLessOrEqual();
  11959. this.setDepthWrite(true);
  11960. // Texture maps
  11961. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11962. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11963. this._nextFreeTextureSlots.push(slot);
  11964. }
  11965. };
  11966. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11967. /**
  11968. * Gets version of the current webGL context
  11969. */
  11970. get: function () {
  11971. return this._webGLVersion;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11977. /**
  11978. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11979. */
  11980. get: function () {
  11981. return this._isStencilEnable;
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Engine.prototype._prepareWorkingCanvas = function () {
  11987. if (this._workingCanvas) {
  11988. return;
  11989. }
  11990. this._workingCanvas = document.createElement("canvas");
  11991. var context = this._workingCanvas.getContext("2d");
  11992. if (context) {
  11993. this._workingContext = context;
  11994. }
  11995. };
  11996. /**
  11997. * Reset the texture cache to empty state
  11998. */
  11999. Engine.prototype.resetTextureCache = function () {
  12000. for (var key in this._boundTexturesCache) {
  12001. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12002. continue;
  12003. }
  12004. var boundTexture = this._boundTexturesCache[key];
  12005. if (boundTexture) {
  12006. this._removeDesignatedSlot(boundTexture);
  12007. }
  12008. this._boundTexturesCache[key] = null;
  12009. }
  12010. if (!this.disableTextureBindingOptimization) {
  12011. this._nextFreeTextureSlots = [];
  12012. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12013. this._nextFreeTextureSlots.push(slot);
  12014. }
  12015. }
  12016. this._currentTextureChannel = -1;
  12017. };
  12018. /**
  12019. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12020. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12021. * @returns true if engine is in deterministic lock step mode
  12022. */
  12023. Engine.prototype.isDeterministicLockStep = function () {
  12024. return this._deterministicLockstep;
  12025. };
  12026. /**
  12027. * Gets the max steps when engine is running in deterministic lock step
  12028. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12029. * @returns the max steps
  12030. */
  12031. Engine.prototype.getLockstepMaxSteps = function () {
  12032. return this._lockstepMaxSteps;
  12033. };
  12034. /**
  12035. * Gets an object containing information about the current webGL context
  12036. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12037. */
  12038. Engine.prototype.getGlInfo = function () {
  12039. return {
  12040. vendor: this._glVendor,
  12041. renderer: this._glRenderer,
  12042. version: this._glVersion
  12043. };
  12044. };
  12045. /**
  12046. * Gets current aspect ratio
  12047. * @param camera defines the camera to use to get the aspect ratio
  12048. * @param useScreen defines if screen size must be used (or the current render target if any)
  12049. * @returns a number defining the aspect ratio
  12050. */
  12051. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12052. if (useScreen === void 0) { useScreen = false; }
  12053. var viewport = camera.viewport;
  12054. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12055. };
  12056. /**
  12057. * Gets current screen aspect ratio
  12058. * @returns a number defining the aspect ratio
  12059. */
  12060. Engine.prototype.getScreenAspectRatio = function () {
  12061. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12062. };
  12063. /**
  12064. * Gets the current render width
  12065. * @param useScreen defines if screen size must be used (or the current render target if any)
  12066. * @returns a number defining the current render width
  12067. */
  12068. Engine.prototype.getRenderWidth = function (useScreen) {
  12069. if (useScreen === void 0) { useScreen = false; }
  12070. if (!useScreen && this._currentRenderTarget) {
  12071. return this._currentRenderTarget.width;
  12072. }
  12073. return this._gl.drawingBufferWidth;
  12074. };
  12075. /**
  12076. * Gets the current render height
  12077. * @param useScreen defines if screen size must be used (or the current render target if any)
  12078. * @returns a number defining the current render height
  12079. */
  12080. Engine.prototype.getRenderHeight = function (useScreen) {
  12081. if (useScreen === void 0) { useScreen = false; }
  12082. if (!useScreen && this._currentRenderTarget) {
  12083. return this._currentRenderTarget.height;
  12084. }
  12085. return this._gl.drawingBufferHeight;
  12086. };
  12087. /**
  12088. * Gets the HTML canvas attached with the current webGL context
  12089. * @returns a HTML canvas
  12090. */
  12091. Engine.prototype.getRenderingCanvas = function () {
  12092. return this._renderingCanvas;
  12093. };
  12094. /**
  12095. * Gets the client rect of the HTML canvas attached with the current webGL context
  12096. * @returns a client rectanglee
  12097. */
  12098. Engine.prototype.getRenderingCanvasClientRect = function () {
  12099. if (!this._renderingCanvas) {
  12100. return null;
  12101. }
  12102. return this._renderingCanvas.getBoundingClientRect();
  12103. };
  12104. /**
  12105. * Defines the hardware scaling level.
  12106. * By default the hardware scaling level is computed from the window device ratio.
  12107. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12108. * @param level defines the level to use
  12109. */
  12110. Engine.prototype.setHardwareScalingLevel = function (level) {
  12111. this._hardwareScalingLevel = level;
  12112. this.resize();
  12113. };
  12114. /**
  12115. * Gets the current hardware scaling level.
  12116. * By default the hardware scaling level is computed from the window device ratio.
  12117. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12118. * @returns a number indicating the current hardware scaling level
  12119. */
  12120. Engine.prototype.getHardwareScalingLevel = function () {
  12121. return this._hardwareScalingLevel;
  12122. };
  12123. /**
  12124. * Gets the list of loaded textures
  12125. * @returns an array containing all loaded textures
  12126. */
  12127. Engine.prototype.getLoadedTexturesCache = function () {
  12128. return this._internalTexturesCache;
  12129. };
  12130. /**
  12131. * Gets the object containing all engine capabilities
  12132. * @returns the EngineCapabilities object
  12133. */
  12134. Engine.prototype.getCaps = function () {
  12135. return this._caps;
  12136. };
  12137. Object.defineProperty(Engine.prototype, "drawCalls", {
  12138. /** @hidden */
  12139. get: function () {
  12140. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12141. return 0;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12147. /** @hidden */
  12148. get: function () {
  12149. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12150. return null;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. /**
  12156. * Gets the current depth function
  12157. * @returns a number defining the depth function
  12158. */
  12159. Engine.prototype.getDepthFunction = function () {
  12160. return this._depthCullingState.depthFunc;
  12161. };
  12162. /**
  12163. * Sets the current depth function
  12164. * @param depthFunc defines the function to use
  12165. */
  12166. Engine.prototype.setDepthFunction = function (depthFunc) {
  12167. this._depthCullingState.depthFunc = depthFunc;
  12168. };
  12169. /**
  12170. * Sets the current depth function to GREATER
  12171. */
  12172. Engine.prototype.setDepthFunctionToGreater = function () {
  12173. this._depthCullingState.depthFunc = this._gl.GREATER;
  12174. };
  12175. /**
  12176. * Sets the current depth function to GEQUAL
  12177. */
  12178. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12179. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12180. };
  12181. /**
  12182. * Sets the current depth function to LESS
  12183. */
  12184. Engine.prototype.setDepthFunctionToLess = function () {
  12185. this._depthCullingState.depthFunc = this._gl.LESS;
  12186. };
  12187. /**
  12188. * Sets the current depth function to LEQUAL
  12189. */
  12190. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12191. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12192. };
  12193. /**
  12194. * Gets a boolean indicating if stencil buffer is enabled
  12195. * @returns the current stencil buffer state
  12196. */
  12197. Engine.prototype.getStencilBuffer = function () {
  12198. return this._stencilState.stencilTest;
  12199. };
  12200. /**
  12201. * Enable or disable the stencil buffer
  12202. * @param enable defines if the stencil buffer must be enabled or disabled
  12203. */
  12204. Engine.prototype.setStencilBuffer = function (enable) {
  12205. this._stencilState.stencilTest = enable;
  12206. };
  12207. /**
  12208. * Gets the current stencil mask
  12209. * @returns a number defining the new stencil mask to use
  12210. */
  12211. Engine.prototype.getStencilMask = function () {
  12212. return this._stencilState.stencilMask;
  12213. };
  12214. /**
  12215. * Sets the current stencil mask
  12216. * @param mask defines the new stencil mask to use
  12217. */
  12218. Engine.prototype.setStencilMask = function (mask) {
  12219. this._stencilState.stencilMask = mask;
  12220. };
  12221. /**
  12222. * Gets the current stencil function
  12223. * @returns a number defining the stencil function to use
  12224. */
  12225. Engine.prototype.getStencilFunction = function () {
  12226. return this._stencilState.stencilFunc;
  12227. };
  12228. /**
  12229. * Gets the current stencil reference value
  12230. * @returns a number defining the stencil reference value to use
  12231. */
  12232. Engine.prototype.getStencilFunctionReference = function () {
  12233. return this._stencilState.stencilFuncRef;
  12234. };
  12235. /**
  12236. * Gets the current stencil mask
  12237. * @returns a number defining the stencil mask to use
  12238. */
  12239. Engine.prototype.getStencilFunctionMask = function () {
  12240. return this._stencilState.stencilFuncMask;
  12241. };
  12242. /**
  12243. * Sets the current stencil function
  12244. * @param stencilFunc defines the new stencil function to use
  12245. */
  12246. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12247. this._stencilState.stencilFunc = stencilFunc;
  12248. };
  12249. /**
  12250. * Sets the current stencil reference
  12251. * @param reference defines the new stencil reference to use
  12252. */
  12253. Engine.prototype.setStencilFunctionReference = function (reference) {
  12254. this._stencilState.stencilFuncRef = reference;
  12255. };
  12256. /**
  12257. * Sets the current stencil mask
  12258. * @param mask defines the new stencil mask to use
  12259. */
  12260. Engine.prototype.setStencilFunctionMask = function (mask) {
  12261. this._stencilState.stencilFuncMask = mask;
  12262. };
  12263. /**
  12264. * Gets the current stencil operation when stencil fails
  12265. * @returns a number defining stencil operation to use when stencil fails
  12266. */
  12267. Engine.prototype.getStencilOperationFail = function () {
  12268. return this._stencilState.stencilOpStencilFail;
  12269. };
  12270. /**
  12271. * Gets the current stencil operation when depth fails
  12272. * @returns a number defining stencil operation to use when depth fails
  12273. */
  12274. Engine.prototype.getStencilOperationDepthFail = function () {
  12275. return this._stencilState.stencilOpDepthFail;
  12276. };
  12277. /**
  12278. * Gets the current stencil operation when stencil passes
  12279. * @returns a number defining stencil operation to use when stencil passes
  12280. */
  12281. Engine.prototype.getStencilOperationPass = function () {
  12282. return this._stencilState.stencilOpStencilDepthPass;
  12283. };
  12284. /**
  12285. * Sets the stencil operation to use when stencil fails
  12286. * @param operation defines the stencil operation to use when stencil fails
  12287. */
  12288. Engine.prototype.setStencilOperationFail = function (operation) {
  12289. this._stencilState.stencilOpStencilFail = operation;
  12290. };
  12291. /**
  12292. * Sets the stencil operation to use when depth fails
  12293. * @param operation defines the stencil operation to use when depth fails
  12294. */
  12295. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12296. this._stencilState.stencilOpDepthFail = operation;
  12297. };
  12298. /**
  12299. * Sets the stencil operation to use when stencil passes
  12300. * @param operation defines the stencil operation to use when stencil passes
  12301. */
  12302. Engine.prototype.setStencilOperationPass = function (operation) {
  12303. this._stencilState.stencilOpStencilDepthPass = operation;
  12304. };
  12305. /**
  12306. * Sets a boolean indicating if the dithering state is enabled or disabled
  12307. * @param value defines the dithering state
  12308. */
  12309. Engine.prototype.setDitheringState = function (value) {
  12310. if (value) {
  12311. this._gl.enable(this._gl.DITHER);
  12312. }
  12313. else {
  12314. this._gl.disable(this._gl.DITHER);
  12315. }
  12316. };
  12317. /**
  12318. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12319. * @param value defines the rasterizer state
  12320. */
  12321. Engine.prototype.setRasterizerState = function (value) {
  12322. if (value) {
  12323. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12324. }
  12325. else {
  12326. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12327. }
  12328. };
  12329. /**
  12330. * stop executing a render loop function and remove it from the execution array
  12331. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12332. */
  12333. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12334. if (!renderFunction) {
  12335. this._activeRenderLoops = [];
  12336. return;
  12337. }
  12338. var index = this._activeRenderLoops.indexOf(renderFunction);
  12339. if (index >= 0) {
  12340. this._activeRenderLoops.splice(index, 1);
  12341. }
  12342. };
  12343. /** @hidden */
  12344. Engine.prototype._renderLoop = function () {
  12345. if (!this._contextWasLost) {
  12346. var shouldRender = true;
  12347. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12348. shouldRender = false;
  12349. }
  12350. if (shouldRender) {
  12351. // Start new frame
  12352. this.beginFrame();
  12353. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12354. var renderFunction = this._activeRenderLoops[index];
  12355. renderFunction();
  12356. }
  12357. // Present
  12358. this.endFrame();
  12359. }
  12360. }
  12361. if (this._activeRenderLoops.length > 0) {
  12362. // Register new frame
  12363. var requester = null;
  12364. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12365. requester = this._vrDisplay;
  12366. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12367. }
  12368. else {
  12369. this._renderingQueueLaunched = false;
  12370. }
  12371. };
  12372. /**
  12373. * Register and execute a render loop. The engine can have more than one render function
  12374. * @param renderFunction defines the function to continuously execute
  12375. */
  12376. Engine.prototype.runRenderLoop = function (renderFunction) {
  12377. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12378. return;
  12379. }
  12380. this._activeRenderLoops.push(renderFunction);
  12381. if (!this._renderingQueueLaunched) {
  12382. this._renderingQueueLaunched = true;
  12383. this._bindedRenderFunction = this._renderLoop.bind(this);
  12384. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12385. }
  12386. };
  12387. /**
  12388. * Toggle full screen mode
  12389. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12390. * @param options defines an option object to be sent to the requestFullscreen function
  12391. */
  12392. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12393. if (this.isFullscreen) {
  12394. BABYLON.Tools.ExitFullscreen();
  12395. }
  12396. else {
  12397. this._pointerLockRequested = requestPointerLock;
  12398. if (this._renderingCanvas) {
  12399. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12400. }
  12401. }
  12402. };
  12403. /**
  12404. * Clear the current render buffer or the current render target (if any is set up)
  12405. * @param color defines the color to use
  12406. * @param backBuffer defines if the back buffer must be cleared
  12407. * @param depth defines if the depth buffer must be cleared
  12408. * @param stencil defines if the stencil buffer must be cleared
  12409. */
  12410. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12411. if (stencil === void 0) { stencil = false; }
  12412. this.applyStates();
  12413. var mode = 0;
  12414. if (backBuffer && color) {
  12415. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12416. mode |= this._gl.COLOR_BUFFER_BIT;
  12417. }
  12418. if (depth) {
  12419. this._gl.clearDepth(1.0);
  12420. mode |= this._gl.DEPTH_BUFFER_BIT;
  12421. }
  12422. if (stencil) {
  12423. this._gl.clearStencil(0);
  12424. mode |= this._gl.STENCIL_BUFFER_BIT;
  12425. }
  12426. this._gl.clear(mode);
  12427. };
  12428. /**
  12429. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12430. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12431. * @param y defines the y-coordinate of the corner of the clear rectangle
  12432. * @param width defines the width of the clear rectangle
  12433. * @param height defines the height of the clear rectangle
  12434. * @param clearColor defines the clear color
  12435. */
  12436. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12437. var gl = this._gl;
  12438. // Save state
  12439. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12440. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12441. // Change state
  12442. gl.enable(gl.SCISSOR_TEST);
  12443. gl.scissor(x, y, width, height);
  12444. // Clear
  12445. this.clear(clearColor, true, true, true);
  12446. // Restore state
  12447. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12448. if (curScissor === true) {
  12449. gl.enable(gl.SCISSOR_TEST);
  12450. }
  12451. else {
  12452. gl.disable(gl.SCISSOR_TEST);
  12453. }
  12454. };
  12455. /** @hidden */
  12456. Engine.prototype._viewport = function (x, y, width, height) {
  12457. if (x !== this._viewportCached.x ||
  12458. y !== this._viewportCached.y ||
  12459. width !== this._viewportCached.z ||
  12460. height !== this._viewportCached.w) {
  12461. this._viewportCached.x = x;
  12462. this._viewportCached.y = y;
  12463. this._viewportCached.z = width;
  12464. this._viewportCached.w = height;
  12465. this._gl.viewport(x, y, width, height);
  12466. }
  12467. };
  12468. /**
  12469. * Set the WebGL's viewport
  12470. * @param viewport defines the viewport element to be used
  12471. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12472. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12473. */
  12474. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12475. var width = requiredWidth || this.getRenderWidth();
  12476. var height = requiredHeight || this.getRenderHeight();
  12477. var x = viewport.x || 0;
  12478. var y = viewport.y || 0;
  12479. this._cachedViewport = viewport;
  12480. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12481. };
  12482. /**
  12483. * Directly set the WebGL Viewport
  12484. * @param x defines the x coordinate of the viewport (in screen space)
  12485. * @param y defines the y coordinate of the viewport (in screen space)
  12486. * @param width defines the width of the viewport (in screen space)
  12487. * @param height defines the height of the viewport (in screen space)
  12488. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  12489. */
  12490. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12491. var currentViewport = this._cachedViewport;
  12492. this._cachedViewport = null;
  12493. this._viewport(x, y, width, height);
  12494. return currentViewport;
  12495. };
  12496. /**
  12497. * Begin a new frame
  12498. */
  12499. Engine.prototype.beginFrame = function () {
  12500. this.onBeginFrameObservable.notifyObservers(this);
  12501. this._measureFps();
  12502. };
  12503. /**
  12504. * Enf the current frame
  12505. */
  12506. Engine.prototype.endFrame = function () {
  12507. // Force a flush in case we are using a bad OS.
  12508. if (this._badOS) {
  12509. this.flushFramebuffer();
  12510. }
  12511. // Submit frame to the vr device, if enabled
  12512. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12513. // TODO: We should only submit the frame if we read frameData successfully.
  12514. this._vrDisplay.submitFrame();
  12515. }
  12516. this.onEndFrameObservable.notifyObservers(this);
  12517. };
  12518. /**
  12519. * Resize the view according to the canvas' size
  12520. */
  12521. Engine.prototype.resize = function () {
  12522. // We're not resizing the size of the canvas while in VR mode & presenting
  12523. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12524. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12525. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12526. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12527. }
  12528. };
  12529. /**
  12530. * Force a specific size of the canvas
  12531. * @param width defines the new canvas' width
  12532. * @param height defines the new canvas' height
  12533. */
  12534. Engine.prototype.setSize = function (width, height) {
  12535. if (!this._renderingCanvas) {
  12536. return;
  12537. }
  12538. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12539. return;
  12540. }
  12541. this._renderingCanvas.width = width;
  12542. this._renderingCanvas.height = height;
  12543. for (var index = 0; index < this.scenes.length; index++) {
  12544. var scene = this.scenes[index];
  12545. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12546. var cam = scene.cameras[camIndex];
  12547. cam._currentRenderId = 0;
  12548. }
  12549. }
  12550. if (this.onResizeObservable.hasObservers) {
  12551. this.onResizeObservable.notifyObservers(this);
  12552. }
  12553. };
  12554. // WebVR functions
  12555. /**
  12556. * Gets a boolean indicating if a webVR device was detected
  12557. * @returns true if a webVR device was detected
  12558. */
  12559. Engine.prototype.isVRDevicePresent = function () {
  12560. return !!this._vrDisplay;
  12561. };
  12562. /**
  12563. * Gets the current webVR device
  12564. * @returns the current webVR device (or null)
  12565. */
  12566. Engine.prototype.getVRDevice = function () {
  12567. return this._vrDisplay;
  12568. };
  12569. /**
  12570. * Initializes a webVR display and starts listening to display change events
  12571. * The onVRDisplayChangedObservable will be notified upon these changes
  12572. * @returns The onVRDisplayChangedObservable
  12573. */
  12574. Engine.prototype.initWebVR = function () {
  12575. this.initWebVRAsync();
  12576. return this.onVRDisplayChangedObservable;
  12577. };
  12578. /**
  12579. * Initializes a webVR display and starts listening to display change events
  12580. * The onVRDisplayChangedObservable will be notified upon these changes
  12581. * @returns A promise containing a VRDisplay and if vr is supported
  12582. */
  12583. Engine.prototype.initWebVRAsync = function () {
  12584. var _this = this;
  12585. var notifyObservers = function () {
  12586. var eventArgs = {
  12587. vrDisplay: _this._vrDisplay,
  12588. vrSupported: _this._vrSupported
  12589. };
  12590. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12591. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12592. };
  12593. if (!this._onVrDisplayConnect) {
  12594. this._onVrDisplayConnect = function (event) {
  12595. _this._vrDisplay = event.display;
  12596. notifyObservers();
  12597. };
  12598. this._onVrDisplayDisconnect = function () {
  12599. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12600. _this._vrDisplay = undefined;
  12601. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12602. notifyObservers();
  12603. };
  12604. this._onVrDisplayPresentChange = function () {
  12605. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12606. };
  12607. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12608. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12609. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12610. }
  12611. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12612. this._webVRInitPromise.then(notifyObservers);
  12613. return this._webVRInitPromise;
  12614. };
  12615. /**
  12616. * Call this function to switch to webVR mode
  12617. * Will do nothing if webVR is not supported or if there is no webVR device
  12618. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12619. */
  12620. Engine.prototype.enableVR = function () {
  12621. var _this = this;
  12622. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12623. var onResolved = function () {
  12624. _this.onVRRequestPresentComplete.notifyObservers(true);
  12625. _this._onVRFullScreenTriggered();
  12626. };
  12627. var onRejected = function () {
  12628. _this.onVRRequestPresentComplete.notifyObservers(false);
  12629. };
  12630. this.onVRRequestPresentStart.notifyObservers(this);
  12631. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12632. }
  12633. };
  12634. /**
  12635. * Call this function to leave webVR mode
  12636. * Will do nothing if webVR is not supported or if there is no webVR device
  12637. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12638. */
  12639. Engine.prototype.disableVR = function () {
  12640. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12641. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12642. }
  12643. };
  12644. Engine.prototype._getVRDisplaysAsync = function () {
  12645. var _this = this;
  12646. return new Promise(function (res, rej) {
  12647. if (navigator.getVRDisplays) {
  12648. navigator.getVRDisplays().then(function (devices) {
  12649. _this._vrSupported = true;
  12650. // note that devices may actually be an empty array. This is fine;
  12651. // we expect this._vrDisplay to be undefined in this case.
  12652. _this._vrDisplay = devices[0];
  12653. res({
  12654. vrDisplay: _this._vrDisplay,
  12655. vrSupported: _this._vrSupported
  12656. });
  12657. });
  12658. }
  12659. else {
  12660. _this._vrDisplay = undefined;
  12661. _this._vrSupported = false;
  12662. res({
  12663. vrDisplay: _this._vrDisplay,
  12664. vrSupported: _this._vrSupported
  12665. });
  12666. }
  12667. });
  12668. };
  12669. /**
  12670. * Binds the frame buffer to the specified texture.
  12671. * @param texture The texture to render to or null for the default canvas
  12672. * @param faceIndex The face of the texture to render to in case of cube texture
  12673. * @param requiredWidth The width of the target to render to
  12674. * @param requiredHeight The height of the target to render to
  12675. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12676. * @param depthStencilTexture The depth stencil texture to use to render
  12677. * @param lodLevel defines le lod level to bind to the frame buffer
  12678. */
  12679. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12680. if (lodLevel === void 0) { lodLevel = 0; }
  12681. if (this._currentRenderTarget) {
  12682. this.unBindFramebuffer(this._currentRenderTarget);
  12683. }
  12684. this._currentRenderTarget = texture;
  12685. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12686. var gl = this._gl;
  12687. if (texture.isCube) {
  12688. if (faceIndex === undefined) {
  12689. faceIndex = 0;
  12690. }
  12691. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12692. if (depthStencilTexture) {
  12693. if (depthStencilTexture._generateStencilBuffer) {
  12694. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12695. }
  12696. else {
  12697. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12698. }
  12699. }
  12700. }
  12701. if (this._cachedViewport && !forceFullscreenViewport) {
  12702. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12703. }
  12704. else {
  12705. if (!requiredWidth) {
  12706. requiredWidth = texture.width;
  12707. if (lodLevel) {
  12708. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12709. }
  12710. }
  12711. if (!requiredHeight) {
  12712. requiredHeight = texture.height;
  12713. if (lodLevel) {
  12714. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12715. }
  12716. }
  12717. this._viewport(0, 0, requiredWidth, requiredHeight);
  12718. }
  12719. this.wipeCaches();
  12720. };
  12721. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12722. if (this._currentFramebuffer !== framebuffer) {
  12723. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12724. this._currentFramebuffer = framebuffer;
  12725. }
  12726. };
  12727. /**
  12728. * Unbind the current render target texture from the webGL context
  12729. * @param texture defines the render target texture to unbind
  12730. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12731. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12732. */
  12733. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12734. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12735. this._currentRenderTarget = null;
  12736. // If MSAA, we need to bitblt back to main texture
  12737. var gl = this._gl;
  12738. if (texture._MSAAFramebuffer) {
  12739. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12740. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12741. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12742. }
  12743. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12744. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12745. gl.generateMipmap(gl.TEXTURE_2D);
  12746. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12747. }
  12748. if (onBeforeUnbind) {
  12749. if (texture._MSAAFramebuffer) {
  12750. // Bind the correct framebuffer
  12751. this.bindUnboundFramebuffer(texture._framebuffer);
  12752. }
  12753. onBeforeUnbind();
  12754. }
  12755. this.bindUnboundFramebuffer(null);
  12756. };
  12757. /**
  12758. * Unbind a list of render target textures from the webGL context
  12759. * This is used only when drawBuffer extension or webGL2 are active
  12760. * @param textures defines the render target textures to unbind
  12761. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12762. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12763. */
  12764. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12765. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12766. this._currentRenderTarget = null;
  12767. // If MSAA, we need to bitblt back to main texture
  12768. var gl = this._gl;
  12769. if (textures[0]._MSAAFramebuffer) {
  12770. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12771. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12772. var attachments = textures[0]._attachments;
  12773. if (!attachments) {
  12774. attachments = new Array(textures.length);
  12775. textures[0]._attachments = attachments;
  12776. }
  12777. for (var i = 0; i < textures.length; i++) {
  12778. var texture = textures[i];
  12779. for (var j = 0; j < attachments.length; j++) {
  12780. attachments[j] = gl.NONE;
  12781. }
  12782. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12783. gl.readBuffer(attachments[i]);
  12784. gl.drawBuffers(attachments);
  12785. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12786. }
  12787. for (var i = 0; i < attachments.length; i++) {
  12788. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12789. }
  12790. gl.drawBuffers(attachments);
  12791. }
  12792. for (var i = 0; i < textures.length; i++) {
  12793. var texture = textures[i];
  12794. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12795. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12796. gl.generateMipmap(gl.TEXTURE_2D);
  12797. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12798. }
  12799. }
  12800. if (onBeforeUnbind) {
  12801. if (textures[0]._MSAAFramebuffer) {
  12802. // Bind the correct framebuffer
  12803. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12804. }
  12805. onBeforeUnbind();
  12806. }
  12807. this.bindUnboundFramebuffer(null);
  12808. };
  12809. /**
  12810. * Force the mipmap generation for the given render target texture
  12811. * @param texture defines the render target texture to use
  12812. */
  12813. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12814. if (texture.generateMipMaps) {
  12815. var gl = this._gl;
  12816. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12817. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12818. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12819. }
  12820. };
  12821. /**
  12822. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12823. */
  12824. Engine.prototype.flushFramebuffer = function () {
  12825. this._gl.flush();
  12826. };
  12827. /**
  12828. * Unbind the current render target and bind the default framebuffer
  12829. */
  12830. Engine.prototype.restoreDefaultFramebuffer = function () {
  12831. if (this._currentRenderTarget) {
  12832. this.unBindFramebuffer(this._currentRenderTarget);
  12833. }
  12834. else {
  12835. this.bindUnboundFramebuffer(null);
  12836. }
  12837. if (this._cachedViewport) {
  12838. this.setViewport(this._cachedViewport);
  12839. }
  12840. this.wipeCaches();
  12841. };
  12842. // UBOs
  12843. /**
  12844. * Create an uniform buffer
  12845. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12846. * @param elements defines the content of the uniform buffer
  12847. * @returns the webGL uniform buffer
  12848. */
  12849. Engine.prototype.createUniformBuffer = function (elements) {
  12850. var ubo = this._gl.createBuffer();
  12851. if (!ubo) {
  12852. throw new Error("Unable to create uniform buffer");
  12853. }
  12854. this.bindUniformBuffer(ubo);
  12855. if (elements instanceof Float32Array) {
  12856. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12857. }
  12858. else {
  12859. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12860. }
  12861. this.bindUniformBuffer(null);
  12862. ubo.references = 1;
  12863. return ubo;
  12864. };
  12865. /**
  12866. * Create a dynamic uniform buffer
  12867. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12868. * @param elements defines the content of the uniform buffer
  12869. * @returns the webGL uniform buffer
  12870. */
  12871. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12872. var ubo = this._gl.createBuffer();
  12873. if (!ubo) {
  12874. throw new Error("Unable to create dynamic uniform buffer");
  12875. }
  12876. this.bindUniformBuffer(ubo);
  12877. if (elements instanceof Float32Array) {
  12878. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12879. }
  12880. else {
  12881. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12882. }
  12883. this.bindUniformBuffer(null);
  12884. ubo.references = 1;
  12885. return ubo;
  12886. };
  12887. /**
  12888. * Update an existing uniform buffer
  12889. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12890. * @param uniformBuffer defines the target uniform buffer
  12891. * @param elements defines the content to update
  12892. * @param offset defines the offset in the uniform buffer where update should start
  12893. * @param count defines the size of the data to update
  12894. */
  12895. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12896. this.bindUniformBuffer(uniformBuffer);
  12897. if (offset === undefined) {
  12898. offset = 0;
  12899. }
  12900. if (count === undefined) {
  12901. if (elements instanceof Float32Array) {
  12902. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12903. }
  12904. else {
  12905. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12906. }
  12907. }
  12908. else {
  12909. if (elements instanceof Float32Array) {
  12910. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12911. }
  12912. else {
  12913. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12914. }
  12915. }
  12916. this.bindUniformBuffer(null);
  12917. };
  12918. // VBOs
  12919. Engine.prototype._resetVertexBufferBinding = function () {
  12920. this.bindArrayBuffer(null);
  12921. this._cachedVertexBuffers = null;
  12922. };
  12923. /**
  12924. * Creates a vertex buffer
  12925. * @param data the data for the vertex buffer
  12926. * @returns the new WebGL static buffer
  12927. */
  12928. Engine.prototype.createVertexBuffer = function (data) {
  12929. var vbo = this._gl.createBuffer();
  12930. if (!vbo) {
  12931. throw new Error("Unable to create vertex buffer");
  12932. }
  12933. this.bindArrayBuffer(vbo);
  12934. if (data instanceof Array) {
  12935. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12936. }
  12937. else {
  12938. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12939. }
  12940. this._resetVertexBufferBinding();
  12941. vbo.references = 1;
  12942. return vbo;
  12943. };
  12944. /**
  12945. * Creates a dynamic vertex buffer
  12946. * @param data the data for the dynamic vertex buffer
  12947. * @returns the new WebGL dynamic buffer
  12948. */
  12949. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12950. var vbo = this._gl.createBuffer();
  12951. if (!vbo) {
  12952. throw new Error("Unable to create dynamic vertex buffer");
  12953. }
  12954. this.bindArrayBuffer(vbo);
  12955. if (data instanceof Array) {
  12956. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12957. }
  12958. else {
  12959. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12960. }
  12961. this._resetVertexBufferBinding();
  12962. vbo.references = 1;
  12963. return vbo;
  12964. };
  12965. /**
  12966. * Update a dynamic index buffer
  12967. * @param indexBuffer defines the target index buffer
  12968. * @param indices defines the data to update
  12969. * @param offset defines the offset in the target index buffer where update should start
  12970. */
  12971. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12972. if (offset === void 0) { offset = 0; }
  12973. // Force cache update
  12974. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12975. this.bindIndexBuffer(indexBuffer);
  12976. var arrayBuffer;
  12977. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12978. arrayBuffer = indices;
  12979. }
  12980. else {
  12981. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12982. }
  12983. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12984. this._resetIndexBufferBinding();
  12985. };
  12986. /**
  12987. * Updates a dynamic vertex buffer.
  12988. * @param vertexBuffer the vertex buffer to update
  12989. * @param data the data used to update the vertex buffer
  12990. * @param byteOffset the byte offset of the data
  12991. * @param byteLength the byte length of the data
  12992. */
  12993. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12994. this.bindArrayBuffer(vertexBuffer);
  12995. if (byteOffset === undefined) {
  12996. byteOffset = 0;
  12997. }
  12998. if (byteLength === undefined) {
  12999. if (data instanceof Array) {
  13000. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13001. }
  13002. else {
  13003. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13004. }
  13005. }
  13006. else {
  13007. if (data instanceof Array) {
  13008. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13009. }
  13010. else {
  13011. if (data instanceof ArrayBuffer) {
  13012. data = new Uint8Array(data, byteOffset, byteLength);
  13013. }
  13014. else {
  13015. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13016. }
  13017. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13018. }
  13019. }
  13020. this._resetVertexBufferBinding();
  13021. };
  13022. Engine.prototype._resetIndexBufferBinding = function () {
  13023. this.bindIndexBuffer(null);
  13024. this._cachedIndexBuffer = null;
  13025. };
  13026. /**
  13027. * Creates a new index buffer
  13028. * @param indices defines the content of the index buffer
  13029. * @param updatable defines if the index buffer must be updatable
  13030. * @returns a new webGL buffer
  13031. */
  13032. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13033. var vbo = this._gl.createBuffer();
  13034. if (!vbo) {
  13035. throw new Error("Unable to create index buffer");
  13036. }
  13037. this.bindIndexBuffer(vbo);
  13038. // Check for 32 bits indices
  13039. var arrayBuffer;
  13040. var need32Bits = false;
  13041. if (indices instanceof Uint16Array) {
  13042. arrayBuffer = indices;
  13043. }
  13044. else {
  13045. //check 32 bit support
  13046. if (this._caps.uintIndices) {
  13047. if (indices instanceof Uint32Array) {
  13048. arrayBuffer = indices;
  13049. need32Bits = true;
  13050. }
  13051. else {
  13052. //number[] or Int32Array, check if 32 bit is necessary
  13053. for (var index = 0; index < indices.length; index++) {
  13054. if (indices[index] > 65535) {
  13055. need32Bits = true;
  13056. break;
  13057. }
  13058. }
  13059. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13060. }
  13061. }
  13062. else {
  13063. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13064. arrayBuffer = new Uint16Array(indices);
  13065. }
  13066. }
  13067. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13068. this._resetIndexBufferBinding();
  13069. vbo.references = 1;
  13070. vbo.is32Bits = need32Bits;
  13071. return vbo;
  13072. };
  13073. /**
  13074. * Bind a webGL buffer to the webGL context
  13075. * @param buffer defines the buffer to bind
  13076. */
  13077. Engine.prototype.bindArrayBuffer = function (buffer) {
  13078. if (!this._vaoRecordInProgress) {
  13079. this._unbindVertexArrayObject();
  13080. }
  13081. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13082. };
  13083. /**
  13084. * Bind an uniform buffer to the current webGL context
  13085. * @param buffer defines the buffer to bind
  13086. */
  13087. Engine.prototype.bindUniformBuffer = function (buffer) {
  13088. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13089. };
  13090. /**
  13091. * Bind a buffer to the current webGL context at a given location
  13092. * @param buffer defines the buffer to bind
  13093. * @param location defines the index where to bind the buffer
  13094. */
  13095. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13096. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13097. };
  13098. /**
  13099. * Bind a specific block at a given index in a specific shader program
  13100. * @param shaderProgram defines the shader program
  13101. * @param blockName defines the block name
  13102. * @param index defines the index where to bind the block
  13103. */
  13104. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13105. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13106. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13107. };
  13108. ;
  13109. Engine.prototype.bindIndexBuffer = function (buffer) {
  13110. if (!this._vaoRecordInProgress) {
  13111. this._unbindVertexArrayObject();
  13112. }
  13113. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13114. };
  13115. Engine.prototype.bindBuffer = function (buffer, target) {
  13116. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13117. this._gl.bindBuffer(target, buffer);
  13118. this._currentBoundBuffer[target] = buffer;
  13119. }
  13120. };
  13121. /**
  13122. * update the bound buffer with the given data
  13123. * @param data defines the data to update
  13124. */
  13125. Engine.prototype.updateArrayBuffer = function (data) {
  13126. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13127. };
  13128. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13129. var pointer = this._currentBufferPointers[indx];
  13130. var changed = false;
  13131. if (!pointer.active) {
  13132. changed = true;
  13133. pointer.active = true;
  13134. pointer.index = indx;
  13135. pointer.size = size;
  13136. pointer.type = type;
  13137. pointer.normalized = normalized;
  13138. pointer.stride = stride;
  13139. pointer.offset = offset;
  13140. pointer.buffer = buffer;
  13141. }
  13142. else {
  13143. if (pointer.buffer !== buffer) {
  13144. pointer.buffer = buffer;
  13145. changed = true;
  13146. }
  13147. if (pointer.size !== size) {
  13148. pointer.size = size;
  13149. changed = true;
  13150. }
  13151. if (pointer.type !== type) {
  13152. pointer.type = type;
  13153. changed = true;
  13154. }
  13155. if (pointer.normalized !== normalized) {
  13156. pointer.normalized = normalized;
  13157. changed = true;
  13158. }
  13159. if (pointer.stride !== stride) {
  13160. pointer.stride = stride;
  13161. changed = true;
  13162. }
  13163. if (pointer.offset !== offset) {
  13164. pointer.offset = offset;
  13165. changed = true;
  13166. }
  13167. }
  13168. if (changed || this._vaoRecordInProgress) {
  13169. this.bindArrayBuffer(buffer);
  13170. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13171. }
  13172. };
  13173. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13174. if (indexBuffer == null) {
  13175. return;
  13176. }
  13177. if (this._cachedIndexBuffer !== indexBuffer) {
  13178. this._cachedIndexBuffer = indexBuffer;
  13179. this.bindIndexBuffer(indexBuffer);
  13180. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13181. }
  13182. };
  13183. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13184. var attributes = effect.getAttributesNames();
  13185. if (!this._vaoRecordInProgress) {
  13186. this._unbindVertexArrayObject();
  13187. }
  13188. this.unbindAllAttributes();
  13189. for (var index = 0; index < attributes.length; index++) {
  13190. var order = effect.getAttributeLocation(index);
  13191. if (order >= 0) {
  13192. var vertexBuffer = vertexBuffers[attributes[index]];
  13193. if (!vertexBuffer) {
  13194. continue;
  13195. }
  13196. this._gl.enableVertexAttribArray(order);
  13197. if (!this._vaoRecordInProgress) {
  13198. this._vertexAttribArraysEnabled[order] = true;
  13199. }
  13200. var buffer = vertexBuffer.getBuffer();
  13201. if (buffer) {
  13202. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13203. if (vertexBuffer.getIsInstanced()) {
  13204. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13205. if (!this._vaoRecordInProgress) {
  13206. this._currentInstanceLocations.push(order);
  13207. this._currentInstanceBuffers.push(buffer);
  13208. }
  13209. }
  13210. }
  13211. }
  13212. }
  13213. };
  13214. /**
  13215. * Records a vertex array object
  13216. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13217. * @param vertexBuffers defines the list of vertex buffers to store
  13218. * @param indexBuffer defines the index buffer to store
  13219. * @param effect defines the effect to store
  13220. * @returns the new vertex array object
  13221. */
  13222. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13223. var vao = this._gl.createVertexArray();
  13224. this._vaoRecordInProgress = true;
  13225. this._gl.bindVertexArray(vao);
  13226. this._mustWipeVertexAttributes = true;
  13227. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13228. this.bindIndexBuffer(indexBuffer);
  13229. this._vaoRecordInProgress = false;
  13230. this._gl.bindVertexArray(null);
  13231. return vao;
  13232. };
  13233. /**
  13234. * Bind a specific vertex array object
  13235. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13236. * @param vertexArrayObject defines the vertex array object to bind
  13237. * @param indexBuffer defines the index buffer to bind
  13238. */
  13239. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13240. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13241. this._cachedVertexArrayObject = vertexArrayObject;
  13242. this._gl.bindVertexArray(vertexArrayObject);
  13243. this._cachedVertexBuffers = null;
  13244. this._cachedIndexBuffer = null;
  13245. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13246. this._mustWipeVertexAttributes = true;
  13247. }
  13248. };
  13249. /**
  13250. * Bind webGl buffers directly to the webGL context
  13251. * @param vertexBuffer defines the vertex buffer to bind
  13252. * @param indexBuffer defines the index buffer to bind
  13253. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13254. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13255. * @param effect defines the effect associated with the vertex buffer
  13256. */
  13257. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13258. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13259. this._cachedVertexBuffers = vertexBuffer;
  13260. this._cachedEffectForVertexBuffers = effect;
  13261. var attributesCount = effect.getAttributesCount();
  13262. this._unbindVertexArrayObject();
  13263. this.unbindAllAttributes();
  13264. var offset = 0;
  13265. for (var index = 0; index < attributesCount; index++) {
  13266. if (index < vertexDeclaration.length) {
  13267. var order = effect.getAttributeLocation(index);
  13268. if (order >= 0) {
  13269. this._gl.enableVertexAttribArray(order);
  13270. this._vertexAttribArraysEnabled[order] = true;
  13271. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13272. }
  13273. offset += vertexDeclaration[index] * 4;
  13274. }
  13275. }
  13276. }
  13277. this._bindIndexBufferWithCache(indexBuffer);
  13278. };
  13279. Engine.prototype._unbindVertexArrayObject = function () {
  13280. if (!this._cachedVertexArrayObject) {
  13281. return;
  13282. }
  13283. this._cachedVertexArrayObject = null;
  13284. this._gl.bindVertexArray(null);
  13285. };
  13286. /**
  13287. * Bind a list of vertex buffers to the webGL context
  13288. * @param vertexBuffers defines the list of vertex buffers to bind
  13289. * @param indexBuffer defines the index buffer to bind
  13290. * @param effect defines the effect associated with the vertex buffers
  13291. */
  13292. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13293. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13294. this._cachedVertexBuffers = vertexBuffers;
  13295. this._cachedEffectForVertexBuffers = effect;
  13296. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13297. }
  13298. this._bindIndexBufferWithCache(indexBuffer);
  13299. };
  13300. /**
  13301. * Unbind all instance attributes
  13302. */
  13303. Engine.prototype.unbindInstanceAttributes = function () {
  13304. var boundBuffer;
  13305. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13306. var instancesBuffer = this._currentInstanceBuffers[i];
  13307. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13308. boundBuffer = instancesBuffer;
  13309. this.bindArrayBuffer(instancesBuffer);
  13310. }
  13311. var offsetLocation = this._currentInstanceLocations[i];
  13312. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13313. }
  13314. this._currentInstanceBuffers.length = 0;
  13315. this._currentInstanceLocations.length = 0;
  13316. };
  13317. /**
  13318. * Release and free the memory of a vertex array object
  13319. * @param vao defines the vertex array object to delete
  13320. */
  13321. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13322. this._gl.deleteVertexArray(vao);
  13323. };
  13324. /** @hidden */
  13325. Engine.prototype._releaseBuffer = function (buffer) {
  13326. buffer.references--;
  13327. if (buffer.references === 0) {
  13328. this._gl.deleteBuffer(buffer);
  13329. return true;
  13330. }
  13331. return false;
  13332. };
  13333. /**
  13334. * Creates a webGL buffer to use with instanciation
  13335. * @param capacity defines the size of the buffer
  13336. * @returns the webGL buffer
  13337. */
  13338. Engine.prototype.createInstancesBuffer = function (capacity) {
  13339. var buffer = this._gl.createBuffer();
  13340. if (!buffer) {
  13341. throw new Error("Unable to create instance buffer");
  13342. }
  13343. buffer.capacity = capacity;
  13344. this.bindArrayBuffer(buffer);
  13345. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13346. return buffer;
  13347. };
  13348. /**
  13349. * Delete a webGL buffer used with instanciation
  13350. * @param buffer defines the webGL buffer to delete
  13351. */
  13352. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13353. this._gl.deleteBuffer(buffer);
  13354. };
  13355. /**
  13356. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13357. * @param instancesBuffer defines the webGL buffer to update and bind
  13358. * @param data defines the data to store in the buffer
  13359. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13360. */
  13361. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13362. this.bindArrayBuffer(instancesBuffer);
  13363. if (data) {
  13364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13365. }
  13366. if (offsetLocations[0].index !== undefined) {
  13367. var stride = 0;
  13368. for (var i = 0; i < offsetLocations.length; i++) {
  13369. var ai = offsetLocations[i];
  13370. stride += ai.attributeSize * 4;
  13371. }
  13372. for (var i = 0; i < offsetLocations.length; i++) {
  13373. var ai = offsetLocations[i];
  13374. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13375. this._gl.enableVertexAttribArray(ai.index);
  13376. this._vertexAttribArraysEnabled[ai.index] = true;
  13377. }
  13378. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13379. this._gl.vertexAttribDivisor(ai.index, 1);
  13380. this._currentInstanceLocations.push(ai.index);
  13381. this._currentInstanceBuffers.push(instancesBuffer);
  13382. }
  13383. }
  13384. else {
  13385. for (var index = 0; index < 4; index++) {
  13386. var offsetLocation = offsetLocations[index];
  13387. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13388. this._gl.enableVertexAttribArray(offsetLocation);
  13389. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13390. }
  13391. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13392. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13393. this._currentInstanceLocations.push(offsetLocation);
  13394. this._currentInstanceBuffers.push(instancesBuffer);
  13395. }
  13396. }
  13397. };
  13398. /**
  13399. * Apply all cached states (depth, culling, stencil and alpha)
  13400. */
  13401. Engine.prototype.applyStates = function () {
  13402. this._depthCullingState.apply(this._gl);
  13403. this._stencilState.apply(this._gl);
  13404. this._alphaState.apply(this._gl);
  13405. };
  13406. /**
  13407. * Send a draw order
  13408. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13409. * @param indexStart defines the starting index
  13410. * @param indexCount defines the number of index to draw
  13411. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13412. */
  13413. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13414. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13415. };
  13416. /**
  13417. * Draw a list of points
  13418. * @param verticesStart defines the index of first vertex to draw
  13419. * @param verticesCount defines the count of vertices to draw
  13420. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13421. */
  13422. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13423. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13424. };
  13425. /**
  13426. * Draw a list of unindexed primitives
  13427. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13428. * @param verticesStart defines the index of first vertex to draw
  13429. * @param verticesCount defines the count of vertices to draw
  13430. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13431. */
  13432. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13433. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13434. };
  13435. /**
  13436. * Draw a list of indexed primitives
  13437. * @param fillMode defines the primitive to use
  13438. * @param indexStart defines the starting index
  13439. * @param indexCount defines the number of index to draw
  13440. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13441. */
  13442. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13443. // Apply states
  13444. this.applyStates();
  13445. this._drawCalls.addCount(1, false);
  13446. // Render
  13447. var drawMode = this._drawMode(fillMode);
  13448. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13449. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13450. if (instancesCount) {
  13451. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13452. }
  13453. else {
  13454. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13455. }
  13456. };
  13457. /**
  13458. * Draw a list of unindexed primitives
  13459. * @param fillMode defines the primitive to use
  13460. * @param verticesStart defines the index of first vertex to draw
  13461. * @param verticesCount defines the count of vertices to draw
  13462. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13463. */
  13464. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13465. // Apply states
  13466. this.applyStates();
  13467. this._drawCalls.addCount(1, false);
  13468. var drawMode = this._drawMode(fillMode);
  13469. if (instancesCount) {
  13470. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13471. }
  13472. else {
  13473. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13474. }
  13475. };
  13476. Engine.prototype._drawMode = function (fillMode) {
  13477. switch (fillMode) {
  13478. // Triangle views
  13479. case BABYLON.Material.TriangleFillMode:
  13480. return this._gl.TRIANGLES;
  13481. case BABYLON.Material.PointFillMode:
  13482. return this._gl.POINTS;
  13483. case BABYLON.Material.WireFrameFillMode:
  13484. return this._gl.LINES;
  13485. // Draw modes
  13486. case BABYLON.Material.PointListDrawMode:
  13487. return this._gl.POINTS;
  13488. case BABYLON.Material.LineListDrawMode:
  13489. return this._gl.LINES;
  13490. case BABYLON.Material.LineLoopDrawMode:
  13491. return this._gl.LINE_LOOP;
  13492. case BABYLON.Material.LineStripDrawMode:
  13493. return this._gl.LINE_STRIP;
  13494. case BABYLON.Material.TriangleStripDrawMode:
  13495. return this._gl.TRIANGLE_STRIP;
  13496. case BABYLON.Material.TriangleFanDrawMode:
  13497. return this._gl.TRIANGLE_FAN;
  13498. default:
  13499. return this._gl.TRIANGLES;
  13500. }
  13501. };
  13502. // Shaders
  13503. /** @hidden */
  13504. Engine.prototype._releaseEffect = function (effect) {
  13505. if (this._compiledEffects[effect._key]) {
  13506. delete this._compiledEffects[effect._key];
  13507. this._deleteProgram(effect.getProgram());
  13508. }
  13509. };
  13510. /** @hidden */
  13511. Engine.prototype._deleteProgram = function (program) {
  13512. if (program) {
  13513. program.__SPECTOR_rebuildProgram = null;
  13514. if (program.transformFeedback) {
  13515. this.deleteTransformFeedback(program.transformFeedback);
  13516. program.transformFeedback = null;
  13517. }
  13518. this._gl.deleteProgram(program);
  13519. }
  13520. };
  13521. /**
  13522. * Create a new effect (used to store vertex/fragment shaders)
  13523. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13524. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13525. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13526. * @param samplers defines an array of string used to represent textures
  13527. * @param defines defines the string containing the defines to use to compile the shaders
  13528. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13529. * @param onCompiled defines a function to call when the effect creation is successful
  13530. * @param onError defines a function to call when the effect creation has failed
  13531. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13532. * @returns the new Effect
  13533. */
  13534. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13535. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13536. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13537. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13538. if (this._compiledEffects[name]) {
  13539. var compiledEffect = this._compiledEffects[name];
  13540. if (onCompiled && compiledEffect.isReady()) {
  13541. onCompiled(compiledEffect);
  13542. }
  13543. return compiledEffect;
  13544. }
  13545. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13546. effect._key = name;
  13547. this._compiledEffects[name] = effect;
  13548. return effect;
  13549. };
  13550. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13551. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13552. };
  13553. ;
  13554. Engine.prototype._compileRawShader = function (source, type) {
  13555. var gl = this._gl;
  13556. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13557. gl.shaderSource(shader, source);
  13558. gl.compileShader(shader);
  13559. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13560. var log = gl.getShaderInfoLog(shader);
  13561. if (log) {
  13562. throw new Error(log);
  13563. }
  13564. }
  13565. if (!shader) {
  13566. throw new Error("Something went wrong while compile the shader.");
  13567. }
  13568. return shader;
  13569. };
  13570. ;
  13571. /**
  13572. * Directly creates a webGL program
  13573. * @param vertexCode defines the vertex shader code to use
  13574. * @param fragmentCode defines the fragment shader code to use
  13575. * @param context defines the webGL context to use (if not set, the current one will be used)
  13576. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13577. * @returns the new webGL program
  13578. */
  13579. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13580. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13581. context = context || this._gl;
  13582. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13583. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13584. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13585. };
  13586. /**
  13587. * Creates a webGL program
  13588. * @param vertexCode defines the vertex shader code to use
  13589. * @param fragmentCode defines the fragment shader code to use
  13590. * @param defines defines the string containing the defines to use to compile the shaders
  13591. * @param context defines the webGL context to use (if not set, the current one will be used)
  13592. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13593. * @returns the new webGL program
  13594. */
  13595. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13596. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13597. context = context || this._gl;
  13598. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13599. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13600. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13601. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13602. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13603. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13604. return program;
  13605. };
  13606. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13607. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13608. var shaderProgram = context.createProgram();
  13609. if (!shaderProgram) {
  13610. throw new Error("Unable to create program");
  13611. }
  13612. context.attachShader(shaderProgram, vertexShader);
  13613. context.attachShader(shaderProgram, fragmentShader);
  13614. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13615. var transformFeedback = this.createTransformFeedback();
  13616. this.bindTransformFeedback(transformFeedback);
  13617. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13618. shaderProgram.transformFeedback = transformFeedback;
  13619. }
  13620. context.linkProgram(shaderProgram);
  13621. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13622. this.bindTransformFeedback(null);
  13623. }
  13624. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13625. if (!linked) {
  13626. var error = context.getProgramInfoLog(shaderProgram);
  13627. if (error) {
  13628. throw new Error(error);
  13629. }
  13630. }
  13631. if (this.validateShaderPrograms) {
  13632. context.validateProgram(shaderProgram);
  13633. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13634. if (!validated) {
  13635. var error = context.getProgramInfoLog(shaderProgram);
  13636. if (error) {
  13637. throw new Error(error);
  13638. }
  13639. }
  13640. }
  13641. context.deleteShader(vertexShader);
  13642. context.deleteShader(fragmentShader);
  13643. return shaderProgram;
  13644. };
  13645. /**
  13646. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13647. * @param shaderProgram defines the webGL program to use
  13648. * @param uniformsNames defines the list of uniform names
  13649. * @returns an array of webGL uniform locations
  13650. */
  13651. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13652. var results = new Array();
  13653. for (var index = 0; index < uniformsNames.length; index++) {
  13654. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13655. }
  13656. return results;
  13657. };
  13658. /**
  13659. * Gets the lsit of active attributes for a given webGL program
  13660. * @param shaderProgram defines the webGL program to use
  13661. * @param attributesNames defines the list of attribute names to get
  13662. * @returns an array of indices indicating the offset of each attribute
  13663. */
  13664. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13665. var results = [];
  13666. for (var index = 0; index < attributesNames.length; index++) {
  13667. try {
  13668. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13669. }
  13670. catch (e) {
  13671. results.push(-1);
  13672. }
  13673. }
  13674. return results;
  13675. };
  13676. /**
  13677. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13678. * @param effect defines the effect to activate
  13679. */
  13680. Engine.prototype.enableEffect = function (effect) {
  13681. if (!effect) {
  13682. return;
  13683. }
  13684. // Use program
  13685. this.bindSamplers(effect);
  13686. this._currentEffect = effect;
  13687. if (effect.onBind) {
  13688. effect.onBind(effect);
  13689. }
  13690. effect.onBindObservable.notifyObservers(effect);
  13691. };
  13692. /**
  13693. * Set the value of an uniform to an array of int32
  13694. * @param uniform defines the webGL uniform location where to store the value
  13695. * @param array defines the array of int32 to store
  13696. */
  13697. Engine.prototype.setIntArray = function (uniform, array) {
  13698. if (!uniform)
  13699. return;
  13700. this._gl.uniform1iv(uniform, array);
  13701. };
  13702. /**
  13703. * Set the value of an uniform to an array of int32 (stored as vec2)
  13704. * @param uniform defines the webGL uniform location where to store the value
  13705. * @param array defines the array of int32 to store
  13706. */
  13707. Engine.prototype.setIntArray2 = function (uniform, array) {
  13708. if (!uniform || array.length % 2 !== 0)
  13709. return;
  13710. this._gl.uniform2iv(uniform, array);
  13711. };
  13712. /**
  13713. * Set the value of an uniform to an array of int32 (stored as vec3)
  13714. * @param uniform defines the webGL uniform location where to store the value
  13715. * @param array defines the array of int32 to store
  13716. */
  13717. Engine.prototype.setIntArray3 = function (uniform, array) {
  13718. if (!uniform || array.length % 3 !== 0)
  13719. return;
  13720. this._gl.uniform3iv(uniform, array);
  13721. };
  13722. /**
  13723. * Set the value of an uniform to an array of int32 (stored as vec4)
  13724. * @param uniform defines the webGL uniform location where to store the value
  13725. * @param array defines the array of int32 to store
  13726. */
  13727. Engine.prototype.setIntArray4 = function (uniform, array) {
  13728. if (!uniform || array.length % 4 !== 0)
  13729. return;
  13730. this._gl.uniform4iv(uniform, array);
  13731. };
  13732. /**
  13733. * Set the value of an uniform to an array of float32
  13734. * @param uniform defines the webGL uniform location where to store the value
  13735. * @param array defines the array of float32 to store
  13736. */
  13737. Engine.prototype.setFloatArray = function (uniform, array) {
  13738. if (!uniform)
  13739. return;
  13740. this._gl.uniform1fv(uniform, array);
  13741. };
  13742. /**
  13743. * Set the value of an uniform to an array of float32 (stored as vec2)
  13744. * @param uniform defines the webGL uniform location where to store the value
  13745. * @param array defines the array of float32 to store
  13746. */
  13747. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13748. if (!uniform || array.length % 2 !== 0)
  13749. return;
  13750. this._gl.uniform2fv(uniform, array);
  13751. };
  13752. /**
  13753. * Set the value of an uniform to an array of float32 (stored as vec3)
  13754. * @param uniform defines the webGL uniform location where to store the value
  13755. * @param array defines the array of float32 to store
  13756. */
  13757. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13758. if (!uniform || array.length % 3 !== 0)
  13759. return;
  13760. this._gl.uniform3fv(uniform, array);
  13761. };
  13762. /**
  13763. * Set the value of an uniform to an array of float32 (stored as vec4)
  13764. * @param uniform defines the webGL uniform location where to store the value
  13765. * @param array defines the array of float32 to store
  13766. */
  13767. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13768. if (!uniform || array.length % 4 !== 0)
  13769. return;
  13770. this._gl.uniform4fv(uniform, array);
  13771. };
  13772. /**
  13773. * Set the value of an uniform to an array of number
  13774. * @param uniform defines the webGL uniform location where to store the value
  13775. * @param array defines the array of number to store
  13776. */
  13777. Engine.prototype.setArray = function (uniform, array) {
  13778. if (!uniform)
  13779. return;
  13780. this._gl.uniform1fv(uniform, array);
  13781. };
  13782. /**
  13783. * Set the value of an uniform to an array of number (stored as vec2)
  13784. * @param uniform defines the webGL uniform location where to store the value
  13785. * @param array defines the array of number to store
  13786. */
  13787. Engine.prototype.setArray2 = function (uniform, array) {
  13788. if (!uniform || array.length % 2 !== 0)
  13789. return;
  13790. this._gl.uniform2fv(uniform, array);
  13791. };
  13792. /**
  13793. * Set the value of an uniform to an array of number (stored as vec3)
  13794. * @param uniform defines the webGL uniform location where to store the value
  13795. * @param array defines the array of number to store
  13796. */
  13797. Engine.prototype.setArray3 = function (uniform, array) {
  13798. if (!uniform || array.length % 3 !== 0)
  13799. return;
  13800. this._gl.uniform3fv(uniform, array);
  13801. };
  13802. /**
  13803. * Set the value of an uniform to an array of number (stored as vec4)
  13804. * @param uniform defines the webGL uniform location where to store the value
  13805. * @param array defines the array of number to store
  13806. */
  13807. Engine.prototype.setArray4 = function (uniform, array) {
  13808. if (!uniform || array.length % 4 !== 0)
  13809. return;
  13810. this._gl.uniform4fv(uniform, array);
  13811. };
  13812. /**
  13813. * Set the value of an uniform to an array of float32 (stored as matrices)
  13814. * @param uniform defines the webGL uniform location where to store the value
  13815. * @param matrices defines the array of float32 to store
  13816. */
  13817. Engine.prototype.setMatrices = function (uniform, matrices) {
  13818. if (!uniform)
  13819. return;
  13820. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13821. };
  13822. /**
  13823. * Set the value of an uniform to a matrix
  13824. * @param uniform defines the webGL uniform location where to store the value
  13825. * @param matrix defines the matrix to store
  13826. */
  13827. Engine.prototype.setMatrix = function (uniform, matrix) {
  13828. if (!uniform)
  13829. return;
  13830. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13831. };
  13832. /**
  13833. * Set the value of an uniform to a matrix (3x3)
  13834. * @param uniform defines the webGL uniform location where to store the value
  13835. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13836. */
  13837. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13838. if (!uniform)
  13839. return;
  13840. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13841. };
  13842. /**
  13843. * Set the value of an uniform to a matrix (2x2)
  13844. * @param uniform defines the webGL uniform location where to store the value
  13845. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13846. */
  13847. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13848. if (!uniform)
  13849. return;
  13850. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13851. };
  13852. /**
  13853. * Set the value of an uniform to a number (int)
  13854. * @param uniform defines the webGL uniform location where to store the value
  13855. * @param value defines the int number to store
  13856. */
  13857. Engine.prototype.setInt = function (uniform, value) {
  13858. if (!uniform)
  13859. return;
  13860. this._gl.uniform1i(uniform, value);
  13861. };
  13862. /**
  13863. * Set the value of an uniform to a number (float)
  13864. * @param uniform defines the webGL uniform location where to store the value
  13865. * @param value defines the float number to store
  13866. */
  13867. Engine.prototype.setFloat = function (uniform, value) {
  13868. if (!uniform)
  13869. return;
  13870. this._gl.uniform1f(uniform, value);
  13871. };
  13872. /**
  13873. * Set the value of an uniform to a vec2
  13874. * @param uniform defines the webGL uniform location where to store the value
  13875. * @param x defines the 1st component of the value
  13876. * @param y defines the 2nd component of the value
  13877. */
  13878. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13879. if (!uniform)
  13880. return;
  13881. this._gl.uniform2f(uniform, x, y);
  13882. };
  13883. /**
  13884. * Set the value of an uniform to a vec3
  13885. * @param uniform defines the webGL uniform location where to store the value
  13886. * @param x defines the 1st component of the value
  13887. * @param y defines the 2nd component of the value
  13888. * @param z defines the 3rd component of the value
  13889. */
  13890. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13891. if (!uniform)
  13892. return;
  13893. this._gl.uniform3f(uniform, x, y, z);
  13894. };
  13895. /**
  13896. * Set the value of an uniform to a boolean
  13897. * @param uniform defines the webGL uniform location where to store the value
  13898. * @param bool defines the boolean to store
  13899. */
  13900. Engine.prototype.setBool = function (uniform, bool) {
  13901. if (!uniform)
  13902. return;
  13903. this._gl.uniform1i(uniform, bool);
  13904. };
  13905. /**
  13906. * Set the value of an uniform to a vec4
  13907. * @param uniform defines the webGL uniform location where to store the value
  13908. * @param x defines the 1st component of the value
  13909. * @param y defines the 2nd component of the value
  13910. * @param z defines the 3rd component of the value
  13911. * @param w defines the 4th component of the value
  13912. */
  13913. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13914. if (!uniform)
  13915. return;
  13916. this._gl.uniform4f(uniform, x, y, z, w);
  13917. };
  13918. /**
  13919. * Set the value of an uniform to a Color3
  13920. * @param uniform defines the webGL uniform location where to store the value
  13921. * @param color3 defines the color to store
  13922. */
  13923. Engine.prototype.setColor3 = function (uniform, color3) {
  13924. if (!uniform)
  13925. return;
  13926. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13927. };
  13928. /**
  13929. * Set the value of an uniform to a Color3 and an alpha value
  13930. * @param uniform defines the webGL uniform location where to store the value
  13931. * @param color3 defines the color to store
  13932. * @param alpha defines the alpha component to store
  13933. */
  13934. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13935. if (!uniform)
  13936. return;
  13937. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13938. };
  13939. /**
  13940. * Sets a Color4 on a uniform variable
  13941. * @param uniform defines the uniform location
  13942. * @param color4 defines the value to be set
  13943. */
  13944. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13945. if (!uniform)
  13946. return;
  13947. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13948. };
  13949. // States
  13950. /**
  13951. * Set various states to the webGL context
  13952. * @param culling defines backface culling state
  13953. * @param zOffset defines the value to apply to zOffset (0 by default)
  13954. * @param force defines if states must be applied even if cache is up to date
  13955. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13956. */
  13957. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13958. if (zOffset === void 0) { zOffset = 0; }
  13959. if (reverseSide === void 0) { reverseSide = false; }
  13960. // Culling
  13961. if (this._depthCullingState.cull !== culling || force) {
  13962. this._depthCullingState.cull = culling;
  13963. }
  13964. // Cull face
  13965. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13966. if (this._depthCullingState.cullFace !== cullFace || force) {
  13967. this._depthCullingState.cullFace = cullFace;
  13968. }
  13969. // Z offset
  13970. this.setZOffset(zOffset);
  13971. // Front face
  13972. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13973. if (this._depthCullingState.frontFace !== frontFace || force) {
  13974. this._depthCullingState.frontFace = frontFace;
  13975. }
  13976. };
  13977. /**
  13978. * Set the z offset to apply to current rendering
  13979. * @param value defines the offset to apply
  13980. */
  13981. Engine.prototype.setZOffset = function (value) {
  13982. this._depthCullingState.zOffset = value;
  13983. };
  13984. /**
  13985. * Gets the current value of the zOffset
  13986. * @returns the current zOffset state
  13987. */
  13988. Engine.prototype.getZOffset = function () {
  13989. return this._depthCullingState.zOffset;
  13990. };
  13991. /**
  13992. * Enable or disable depth buffering
  13993. * @param enable defines the state to set
  13994. */
  13995. Engine.prototype.setDepthBuffer = function (enable) {
  13996. this._depthCullingState.depthTest = enable;
  13997. };
  13998. /**
  13999. * Gets a boolean indicating if depth writing is enabled
  14000. * @returns the current depth writing state
  14001. */
  14002. Engine.prototype.getDepthWrite = function () {
  14003. return this._depthCullingState.depthMask;
  14004. };
  14005. /**
  14006. * Enable or disable depth writing
  14007. * @param enable defines the state to set
  14008. */
  14009. Engine.prototype.setDepthWrite = function (enable) {
  14010. this._depthCullingState.depthMask = enable;
  14011. };
  14012. /**
  14013. * Enable or disable color writing
  14014. * @param enable defines the state to set
  14015. */
  14016. Engine.prototype.setColorWrite = function (enable) {
  14017. this._gl.colorMask(enable, enable, enable, enable);
  14018. this._colorWrite = enable;
  14019. };
  14020. /**
  14021. * Gets a boolean indicating if color writing is enabled
  14022. * @returns the current color writing state
  14023. */
  14024. Engine.prototype.getColorWrite = function () {
  14025. return this._colorWrite;
  14026. };
  14027. /**
  14028. * Sets alpha constants used by some alpha blending modes
  14029. * @param r defines the red component
  14030. * @param g defines the green component
  14031. * @param b defines the blue component
  14032. * @param a defines the alpha component
  14033. */
  14034. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14035. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14036. };
  14037. /**
  14038. * Sets the current alpha mode
  14039. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14040. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14041. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14042. */
  14043. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14044. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14045. if (this._alphaMode === mode) {
  14046. return;
  14047. }
  14048. switch (mode) {
  14049. case Engine.ALPHA_DISABLE:
  14050. this._alphaState.alphaBlend = false;
  14051. break;
  14052. case Engine.ALPHA_PREMULTIPLIED:
  14053. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14054. this._alphaState.alphaBlend = true;
  14055. break;
  14056. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14057. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14058. this._alphaState.alphaBlend = true;
  14059. break;
  14060. case Engine.ALPHA_COMBINE:
  14061. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14062. this._alphaState.alphaBlend = true;
  14063. break;
  14064. case Engine.ALPHA_ONEONE:
  14065. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14066. this._alphaState.alphaBlend = true;
  14067. break;
  14068. case Engine.ALPHA_ADD:
  14069. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14070. this._alphaState.alphaBlend = true;
  14071. break;
  14072. case Engine.ALPHA_SUBTRACT:
  14073. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14074. this._alphaState.alphaBlend = true;
  14075. break;
  14076. case Engine.ALPHA_MULTIPLY:
  14077. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14078. this._alphaState.alphaBlend = true;
  14079. break;
  14080. case Engine.ALPHA_MAXIMIZED:
  14081. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14082. this._alphaState.alphaBlend = true;
  14083. break;
  14084. case Engine.ALPHA_INTERPOLATE:
  14085. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14086. this._alphaState.alphaBlend = true;
  14087. break;
  14088. case Engine.ALPHA_SCREENMODE:
  14089. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14090. this._alphaState.alphaBlend = true;
  14091. break;
  14092. }
  14093. if (!noDepthWriteChange) {
  14094. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14095. }
  14096. this._alphaMode = mode;
  14097. };
  14098. /**
  14099. * Gets the current alpha mode
  14100. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14101. * @returns the current alpha mode
  14102. */
  14103. Engine.prototype.getAlphaMode = function () {
  14104. return this._alphaMode;
  14105. };
  14106. // Textures
  14107. /**
  14108. * Clears the list of texture accessible through engine.
  14109. * This can help preventing texture load conflict due to name collision.
  14110. */
  14111. Engine.prototype.clearInternalTexturesCache = function () {
  14112. this._internalTexturesCache = [];
  14113. };
  14114. /**
  14115. * Force the entire cache to be cleared
  14116. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14117. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14118. */
  14119. Engine.prototype.wipeCaches = function (bruteForce) {
  14120. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14121. return;
  14122. }
  14123. this._currentEffect = null;
  14124. this._unpackFlipYCached = null;
  14125. this._viewportCached.x = 0;
  14126. this._viewportCached.y = 0;
  14127. this._viewportCached.z = 0;
  14128. this._viewportCached.w = 0;
  14129. if (bruteForce) {
  14130. this.resetTextureCache();
  14131. this._currentProgram = null;
  14132. this._stencilState.reset();
  14133. this._depthCullingState.reset();
  14134. this.setDepthFunctionToLessOrEqual();
  14135. this._alphaState.reset();
  14136. }
  14137. this._resetVertexBufferBinding();
  14138. this._cachedIndexBuffer = null;
  14139. this._cachedEffectForVertexBuffers = null;
  14140. this._unbindVertexArrayObject();
  14141. this.bindIndexBuffer(null);
  14142. };
  14143. /**
  14144. * Set the compressed texture format to use, based on the formats you have, and the formats
  14145. * supported by the hardware / browser.
  14146. *
  14147. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14148. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14149. * to API arguments needed to compressed textures. This puts the burden on the container
  14150. * generator to house the arcane code for determining these for current & future formats.
  14151. *
  14152. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14153. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14154. *
  14155. * Note: The result of this call is not taken into account when a texture is base64.
  14156. *
  14157. * @param formatsAvailable defines the list of those format families you have created
  14158. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14159. *
  14160. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14161. * @returns The extension selected.
  14162. */
  14163. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14164. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14165. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14166. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14167. return this._textureFormatInUse = this._texturesSupported[i];
  14168. }
  14169. }
  14170. }
  14171. // actively set format to nothing, to allow this to be called more than once
  14172. // and possibly fail the 2nd time
  14173. this._textureFormatInUse = null;
  14174. return null;
  14175. };
  14176. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14177. var gl = this._gl;
  14178. var magFilter = gl.NEAREST;
  14179. var minFilter = gl.NEAREST;
  14180. switch (samplingMode) {
  14181. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14182. magFilter = gl.LINEAR;
  14183. if (generateMipMaps) {
  14184. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14185. }
  14186. else {
  14187. minFilter = gl.LINEAR;
  14188. }
  14189. break;
  14190. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14191. magFilter = gl.LINEAR;
  14192. if (generateMipMaps) {
  14193. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14194. }
  14195. else {
  14196. minFilter = gl.LINEAR;
  14197. }
  14198. break;
  14199. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14200. magFilter = gl.NEAREST;
  14201. if (generateMipMaps) {
  14202. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14203. }
  14204. else {
  14205. minFilter = gl.NEAREST;
  14206. }
  14207. break;
  14208. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14209. magFilter = gl.NEAREST;
  14210. if (generateMipMaps) {
  14211. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14212. }
  14213. else {
  14214. minFilter = gl.NEAREST;
  14215. }
  14216. break;
  14217. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14218. magFilter = gl.NEAREST;
  14219. if (generateMipMaps) {
  14220. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14221. }
  14222. else {
  14223. minFilter = gl.LINEAR;
  14224. }
  14225. break;
  14226. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14227. magFilter = gl.NEAREST;
  14228. if (generateMipMaps) {
  14229. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14230. }
  14231. else {
  14232. minFilter = gl.LINEAR;
  14233. }
  14234. break;
  14235. case Engine.TEXTURE_NEAREST_LINEAR:
  14236. magFilter = gl.NEAREST;
  14237. minFilter = gl.LINEAR;
  14238. break;
  14239. case Engine.TEXTURE_NEAREST_NEAREST:
  14240. magFilter = gl.NEAREST;
  14241. minFilter = gl.NEAREST;
  14242. break;
  14243. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14244. magFilter = gl.LINEAR;
  14245. if (generateMipMaps) {
  14246. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14247. }
  14248. else {
  14249. minFilter = gl.NEAREST;
  14250. }
  14251. break;
  14252. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14253. magFilter = gl.LINEAR;
  14254. if (generateMipMaps) {
  14255. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14256. }
  14257. else {
  14258. minFilter = gl.NEAREST;
  14259. }
  14260. break;
  14261. case Engine.TEXTURE_LINEAR_LINEAR:
  14262. magFilter = gl.LINEAR;
  14263. minFilter = gl.LINEAR;
  14264. break;
  14265. case Engine.TEXTURE_LINEAR_NEAREST:
  14266. magFilter = gl.LINEAR;
  14267. minFilter = gl.NEAREST;
  14268. break;
  14269. }
  14270. return {
  14271. min: minFilter,
  14272. mag: magFilter
  14273. };
  14274. };
  14275. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14276. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14277. var img;
  14278. var onload = function () {
  14279. loadedImages[index] = img;
  14280. loadedImages._internalCount++;
  14281. if (scene) {
  14282. scene._removePendingData(img);
  14283. }
  14284. if (loadedImages._internalCount === 6) {
  14285. onfinish(loadedImages);
  14286. }
  14287. };
  14288. var onerror = function (message, exception) {
  14289. if (scene) {
  14290. scene._removePendingData(img);
  14291. }
  14292. if (onErrorCallBack) {
  14293. onErrorCallBack(message, exception);
  14294. }
  14295. };
  14296. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14297. if (scene) {
  14298. scene._addPendingData(img);
  14299. }
  14300. };
  14301. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14302. if (onError === void 0) { onError = null; }
  14303. var loadedImages = [];
  14304. loadedImages._internalCount = 0;
  14305. for (var index = 0; index < 6; index++) {
  14306. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14307. }
  14308. };
  14309. ;
  14310. /** @hidden */
  14311. Engine.prototype._createTexture = function () {
  14312. var texture = this._gl.createTexture();
  14313. if (!texture) {
  14314. throw new Error("Unable to create texture");
  14315. }
  14316. return texture;
  14317. };
  14318. /**
  14319. * Usually called from BABYLON.Texture.ts.
  14320. * Passed information to create a WebGLTexture
  14321. * @param urlArg defines a value which contains one of the following:
  14322. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14323. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14324. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14325. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14326. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14327. * @param scene needed for loading to the correct scene
  14328. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14329. * @param onLoad optional callback to be called upon successful completion
  14330. * @param onError optional callback to be called upon failure
  14331. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14332. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14333. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14334. * @param forcedExtension defines the extension to use to pick the right loader
  14335. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14336. */
  14337. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14338. var _this = this;
  14339. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14340. if (onLoad === void 0) { onLoad = null; }
  14341. if (onError === void 0) { onError = null; }
  14342. if (buffer === void 0) { buffer = null; }
  14343. if (fallback === void 0) { fallback = null; }
  14344. if (format === void 0) { format = null; }
  14345. if (forcedExtension === void 0) { forcedExtension = null; }
  14346. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14347. var fromData = url.substr(0, 5) === "data:";
  14348. var fromBlob = url.substr(0, 5) === "blob:";
  14349. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14350. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14351. // establish the file extension, if possible
  14352. var lastDot = url.lastIndexOf('.');
  14353. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14354. var loader = null;
  14355. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14356. var availableLoader = _a[_i];
  14357. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14358. loader = availableLoader;
  14359. break;
  14360. }
  14361. }
  14362. if (loader) {
  14363. url = loader.transformUrl(url, this._textureFormatInUse);
  14364. }
  14365. if (scene) {
  14366. scene._addPendingData(texture);
  14367. }
  14368. texture.url = url;
  14369. texture.generateMipMaps = !noMipmap;
  14370. texture.samplingMode = samplingMode;
  14371. texture.invertY = invertY;
  14372. if (!this._doNotHandleContextLost) {
  14373. // Keep a link to the buffer only if we plan to handle context lost
  14374. texture._buffer = buffer;
  14375. }
  14376. var onLoadObserver = null;
  14377. if (onLoad && !fallback) {
  14378. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14379. }
  14380. if (!fallback)
  14381. this._internalTexturesCache.push(texture);
  14382. var onInternalError = function (message, exception) {
  14383. if (scene) {
  14384. scene._removePendingData(texture);
  14385. }
  14386. var customFallback = false;
  14387. if (loader) {
  14388. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14389. if (fallbackUrl) {
  14390. // Add Back
  14391. customFallback = true;
  14392. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14393. }
  14394. }
  14395. if (!customFallback) {
  14396. if (onLoadObserver) {
  14397. texture.onLoadedObservable.remove(onLoadObserver);
  14398. }
  14399. if (BABYLON.Tools.UseFallbackTexture) {
  14400. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14401. }
  14402. }
  14403. if (onError) {
  14404. onError(message || "Unknown error", exception);
  14405. }
  14406. };
  14407. // processing for non-image formats
  14408. if (loader) {
  14409. var callback = function (data) {
  14410. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14411. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14412. done();
  14413. return false;
  14414. }, samplingMode);
  14415. });
  14416. };
  14417. if (!buffer) {
  14418. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14419. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14420. });
  14421. }
  14422. else {
  14423. callback(buffer);
  14424. }
  14425. }
  14426. else {
  14427. var onload = function (img) {
  14428. if (fromBlob && !_this._doNotHandleContextLost) {
  14429. // We need to store the image if we need to rebuild the texture
  14430. // in case of a webgl context lost
  14431. texture._buffer = img;
  14432. }
  14433. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14434. var gl = _this._gl;
  14435. var isPot = (img.width === potWidth && img.height === potHeight);
  14436. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14437. if (isPot) {
  14438. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14439. return false;
  14440. }
  14441. var maxTextureSize = _this._caps.maxTextureSize;
  14442. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14443. _this._prepareWorkingCanvas();
  14444. if (!_this._workingCanvas || !_this._workingContext) {
  14445. return false;
  14446. }
  14447. _this._workingCanvas.width = potWidth;
  14448. _this._workingCanvas.height = potHeight;
  14449. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14450. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14451. texture.width = potWidth;
  14452. texture.height = potHeight;
  14453. return false;
  14454. }
  14455. else {
  14456. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14457. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14458. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14459. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14461. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14462. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14463. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14464. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14465. _this._releaseTexture(source_1);
  14466. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14467. continuationCallback();
  14468. });
  14469. }
  14470. return true;
  14471. }, samplingMode);
  14472. };
  14473. if (!fromData || isBase64) {
  14474. if (buffer instanceof HTMLImageElement) {
  14475. onload(buffer);
  14476. }
  14477. else {
  14478. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14479. }
  14480. }
  14481. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14482. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14483. }
  14484. else {
  14485. onload(buffer);
  14486. }
  14487. }
  14488. return texture;
  14489. };
  14490. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14491. var _this = this;
  14492. var rtt = this.createRenderTargetTexture({
  14493. width: destination.width,
  14494. height: destination.height,
  14495. }, {
  14496. generateMipMaps: false,
  14497. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14498. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14499. generateDepthBuffer: false,
  14500. generateStencilBuffer: false
  14501. });
  14502. if (!this._rescalePostProcess) {
  14503. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14504. }
  14505. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14506. _this._rescalePostProcess.onApply = function (effect) {
  14507. effect._bindTexture("textureSampler", source);
  14508. };
  14509. var hostingScene = scene;
  14510. if (!hostingScene) {
  14511. hostingScene = _this.scenes[_this.scenes.length - 1];
  14512. }
  14513. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14514. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14515. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14516. _this.unBindFramebuffer(rtt);
  14517. _this._releaseTexture(rtt);
  14518. if (onComplete) {
  14519. onComplete();
  14520. }
  14521. });
  14522. };
  14523. /**
  14524. * Update a raw texture
  14525. * @param texture defines the texture to update
  14526. * @param data defines the data to store in the texture
  14527. * @param format defines the format of the data
  14528. * @param invertY defines if data must be stored with Y axis inverted
  14529. * @param compression defines the compression used (null by default)
  14530. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14531. */
  14532. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14533. if (compression === void 0) { compression = null; }
  14534. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14535. if (!texture) {
  14536. return;
  14537. }
  14538. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14539. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14540. // babylon's internalFormat but gl's texImage2D format
  14541. var internalFormat = this._getInternalFormat(format);
  14542. var textureType = this._getWebGLTextureType(type);
  14543. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14544. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14545. if (!this._doNotHandleContextLost) {
  14546. texture._bufferView = data;
  14547. texture.format = format;
  14548. texture.type = type;
  14549. texture.invertY = invertY;
  14550. texture._compression = compression;
  14551. }
  14552. if (texture.width % 4 !== 0) {
  14553. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14554. }
  14555. if (compression && data) {
  14556. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14557. }
  14558. else {
  14559. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14560. }
  14561. if (texture.generateMipMaps) {
  14562. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14563. }
  14564. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14565. // this.resetTextureCache();
  14566. texture.isReady = true;
  14567. };
  14568. /**
  14569. * Creates a raw texture
  14570. * @param data defines the data to store in the texture
  14571. * @param width defines the width of the texture
  14572. * @param height defines the height of the texture
  14573. * @param format defines the format of the data
  14574. * @param generateMipMaps defines if the engine should generate the mip levels
  14575. * @param invertY defines if data must be stored with Y axis inverted
  14576. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14577. * @param compression defines the compression used (null by default)
  14578. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14579. * @returns the raw texture inside an InternalTexture
  14580. */
  14581. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14582. if (compression === void 0) { compression = null; }
  14583. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14584. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14585. texture.baseWidth = width;
  14586. texture.baseHeight = height;
  14587. texture.width = width;
  14588. texture.height = height;
  14589. texture.format = format;
  14590. texture.generateMipMaps = generateMipMaps;
  14591. texture.samplingMode = samplingMode;
  14592. texture.invertY = invertY;
  14593. texture._compression = compression;
  14594. texture.type = type;
  14595. if (!this._doNotHandleContextLost) {
  14596. texture._bufferView = data;
  14597. }
  14598. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14599. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14600. // Filters
  14601. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14602. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14603. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14604. if (generateMipMaps) {
  14605. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14606. }
  14607. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14608. this._internalTexturesCache.push(texture);
  14609. return texture;
  14610. };
  14611. /** @hidden */
  14612. Engine.prototype._unpackFlipY = function (value) {
  14613. if (this._unpackFlipYCached !== value) {
  14614. this._unpackFlipYCached = value;
  14615. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14616. }
  14617. };
  14618. /** @hidden */
  14619. Engine.prototype._getUnpackAlignement = function () {
  14620. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14621. };
  14622. /**
  14623. * Creates a dynamic texture
  14624. * @param width defines the width of the texture
  14625. * @param height defines the height of the texture
  14626. * @param generateMipMaps defines if the engine should generate the mip levels
  14627. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14628. * @returns the dynamic texture inside an InternalTexture
  14629. */
  14630. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14631. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14632. texture.baseWidth = width;
  14633. texture.baseHeight = height;
  14634. if (generateMipMaps) {
  14635. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14636. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14637. }
  14638. // this.resetTextureCache();
  14639. texture.width = width;
  14640. texture.height = height;
  14641. texture.isReady = false;
  14642. texture.generateMipMaps = generateMipMaps;
  14643. texture.samplingMode = samplingMode;
  14644. this.updateTextureSamplingMode(samplingMode, texture);
  14645. this._internalTexturesCache.push(texture);
  14646. return texture;
  14647. };
  14648. /**
  14649. * Update the sampling mode of a given texture
  14650. * @param samplingMode defines the required sampling mode
  14651. * @param texture defines the texture to update
  14652. */
  14653. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14654. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14655. if (texture.isCube) {
  14656. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14657. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14659. }
  14660. else if (texture.is3D) {
  14661. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14662. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14663. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14664. }
  14665. else {
  14666. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14667. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14668. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14669. }
  14670. texture.samplingMode = samplingMode;
  14671. };
  14672. /**
  14673. * Update the content of a dynamic texture
  14674. * @param texture defines the texture to update
  14675. * @param canvas defines the canvas containing the source
  14676. * @param invertY defines if data must be stored with Y axis inverted
  14677. * @param premulAlpha defines if alpha is stored as premultiplied
  14678. * @param format defines the format of the data
  14679. */
  14680. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14681. if (premulAlpha === void 0) { premulAlpha = false; }
  14682. if (!texture) {
  14683. return;
  14684. }
  14685. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14686. this._unpackFlipY(invertY);
  14687. if (premulAlpha) {
  14688. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14689. }
  14690. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14691. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14692. if (texture.generateMipMaps) {
  14693. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14694. }
  14695. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14696. if (premulAlpha) {
  14697. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14698. }
  14699. texture.isReady = true;
  14700. };
  14701. /**
  14702. * Update a video texture
  14703. * @param texture defines the texture to update
  14704. * @param video defines the video element to use
  14705. * @param invertY defines if data must be stored with Y axis inverted
  14706. */
  14707. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14708. if (!texture || texture._isDisabled) {
  14709. return;
  14710. }
  14711. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14712. this._unpackFlipY(!invertY); // Video are upside down by default
  14713. try {
  14714. // Testing video texture support
  14715. if (this._videoTextureSupported === undefined) {
  14716. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14717. if (this._gl.getError() !== 0) {
  14718. this._videoTextureSupported = false;
  14719. }
  14720. else {
  14721. this._videoTextureSupported = true;
  14722. }
  14723. }
  14724. // Copy video through the current working canvas if video texture is not supported
  14725. if (!this._videoTextureSupported) {
  14726. if (!texture._workingCanvas) {
  14727. texture._workingCanvas = document.createElement("canvas");
  14728. var context = texture._workingCanvas.getContext("2d");
  14729. if (!context) {
  14730. throw new Error("Unable to get 2d context");
  14731. }
  14732. texture._workingContext = context;
  14733. texture._workingCanvas.width = texture.width;
  14734. texture._workingCanvas.height = texture.height;
  14735. }
  14736. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14737. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14738. }
  14739. else {
  14740. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14741. }
  14742. if (texture.generateMipMaps) {
  14743. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14744. }
  14745. if (!wasPreviouslyBound) {
  14746. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14747. }
  14748. // this.resetTextureCache();
  14749. texture.isReady = true;
  14750. }
  14751. catch (ex) {
  14752. // Something unexpected
  14753. // Let's disable the texture
  14754. texture._isDisabled = true;
  14755. }
  14756. };
  14757. /**
  14758. * Updates a depth texture Comparison Mode and Function.
  14759. * If the comparison Function is equal to 0, the mode will be set to none.
  14760. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14761. * @param texture The texture to set the comparison function for
  14762. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14763. */
  14764. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14765. if (this.webGLVersion === 1) {
  14766. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14767. return;
  14768. }
  14769. var gl = this._gl;
  14770. if (texture.isCube) {
  14771. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14772. if (comparisonFunction === 0) {
  14773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14775. }
  14776. else {
  14777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14779. }
  14780. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14781. }
  14782. else {
  14783. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14784. if (comparisonFunction === 0) {
  14785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14787. }
  14788. else {
  14789. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14790. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14791. }
  14792. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14793. }
  14794. texture._comparisonFunction = comparisonFunction;
  14795. };
  14796. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14797. var width = size.width || size;
  14798. var height = size.height || size;
  14799. internalTexture.baseWidth = width;
  14800. internalTexture.baseHeight = height;
  14801. internalTexture.width = width;
  14802. internalTexture.height = height;
  14803. internalTexture.isReady = true;
  14804. internalTexture.samples = 1;
  14805. internalTexture.generateMipMaps = false;
  14806. internalTexture._generateDepthBuffer = true;
  14807. internalTexture._generateStencilBuffer = generateStencil;
  14808. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14809. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14810. internalTexture._comparisonFunction = comparisonFunction;
  14811. var gl = this._gl;
  14812. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14813. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14814. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14815. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14816. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14817. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14818. if (comparisonFunction === 0) {
  14819. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14820. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14821. }
  14822. else {
  14823. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14824. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14825. }
  14826. };
  14827. /**
  14828. * Creates a depth stencil texture.
  14829. * This is only available in WebGL 2 or with the depth texture extension available.
  14830. * @param size The size of face edge in the texture.
  14831. * @param options The options defining the texture.
  14832. * @returns The texture
  14833. */
  14834. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14835. if (options.isCube) {
  14836. var width = size.width || size;
  14837. return this._createDepthStencilCubeTexture(width, options);
  14838. }
  14839. else {
  14840. return this._createDepthStencilTexture(size, options);
  14841. }
  14842. };
  14843. /**
  14844. * Creates a depth stencil texture.
  14845. * This is only available in WebGL 2 or with the depth texture extension available.
  14846. * @param size The size of face edge in the texture.
  14847. * @param options The options defining the texture.
  14848. * @returns The texture
  14849. */
  14850. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14851. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14852. if (!this._caps.depthTextureExtension) {
  14853. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14854. return internalTexture;
  14855. }
  14856. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14857. var gl = this._gl;
  14858. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14859. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14860. if (this.webGLVersion > 1) {
  14861. if (internalOptions.generateStencil) {
  14862. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14863. }
  14864. else {
  14865. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14866. }
  14867. }
  14868. else {
  14869. if (internalOptions.generateStencil) {
  14870. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14871. }
  14872. else {
  14873. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14874. }
  14875. }
  14876. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14877. return internalTexture;
  14878. };
  14879. /**
  14880. * Creates a depth stencil cube texture.
  14881. * This is only available in WebGL 2.
  14882. * @param size The size of face edge in the cube texture.
  14883. * @param options The options defining the cube texture.
  14884. * @returns The cube texture
  14885. */
  14886. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14887. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14888. internalTexture.isCube = true;
  14889. if (this.webGLVersion === 1) {
  14890. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14891. return internalTexture;
  14892. }
  14893. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14894. var gl = this._gl;
  14895. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14896. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14897. // Create the depth/stencil buffer
  14898. for (var face = 0; face < 6; face++) {
  14899. if (internalOptions.generateStencil) {
  14900. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14901. }
  14902. else {
  14903. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14904. }
  14905. }
  14906. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14907. return internalTexture;
  14908. };
  14909. /**
  14910. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14911. * @param renderTarget The render target to set the frame buffer for
  14912. */
  14913. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14914. // Create the framebuffer
  14915. var internalTexture = renderTarget.getInternalTexture();
  14916. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14917. return;
  14918. }
  14919. var gl = this._gl;
  14920. var depthStencilTexture = renderTarget.depthStencilTexture;
  14921. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14922. if (depthStencilTexture.isCube) {
  14923. if (depthStencilTexture._generateStencilBuffer) {
  14924. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14925. }
  14926. else {
  14927. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14928. }
  14929. }
  14930. else {
  14931. if (depthStencilTexture._generateStencilBuffer) {
  14932. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14933. }
  14934. else {
  14935. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14936. }
  14937. }
  14938. this.bindUnboundFramebuffer(null);
  14939. };
  14940. /**
  14941. * Creates a new render target texture
  14942. * @param size defines the size of the texture
  14943. * @param options defines the options used to create the texture
  14944. * @returns a new render target texture stored in an InternalTexture
  14945. */
  14946. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14947. var fullOptions = new RenderTargetCreationOptions();
  14948. if (options !== undefined && typeof options === "object") {
  14949. fullOptions.generateMipMaps = options.generateMipMaps;
  14950. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14951. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14952. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14953. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14954. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14955. }
  14956. else {
  14957. fullOptions.generateMipMaps = options;
  14958. fullOptions.generateDepthBuffer = true;
  14959. fullOptions.generateStencilBuffer = false;
  14960. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14961. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  14962. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14963. }
  14964. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14965. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14966. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14967. }
  14968. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14969. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14970. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14971. }
  14972. var gl = this._gl;
  14973. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14974. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14975. var width = size.width || size;
  14976. var height = size.height || size;
  14977. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  14978. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14979. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14980. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14981. }
  14982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14983. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14986. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14987. // Create the framebuffer
  14988. var currentFrameBuffer = this._currentFramebuffer;
  14989. var framebuffer = gl.createFramebuffer();
  14990. this.bindUnboundFramebuffer(framebuffer);
  14991. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14992. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14993. if (fullOptions.generateMipMaps) {
  14994. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14995. }
  14996. // Unbind
  14997. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14998. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14999. this.bindUnboundFramebuffer(currentFrameBuffer);
  15000. texture._framebuffer = framebuffer;
  15001. texture.baseWidth = width;
  15002. texture.baseHeight = height;
  15003. texture.width = width;
  15004. texture.height = height;
  15005. texture.isReady = true;
  15006. texture.samples = 1;
  15007. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15008. texture.samplingMode = fullOptions.samplingMode;
  15009. texture.type = fullOptions.type;
  15010. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15011. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15012. // this.resetTextureCache();
  15013. this._internalTexturesCache.push(texture);
  15014. return texture;
  15015. };
  15016. /**
  15017. * Create a multi render target texture
  15018. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15019. * @param size defines the size of the texture
  15020. * @param options defines the creation options
  15021. * @returns the cube texture as an InternalTexture
  15022. */
  15023. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15024. var generateMipMaps = false;
  15025. var generateDepthBuffer = true;
  15026. var generateStencilBuffer = false;
  15027. var generateDepthTexture = false;
  15028. var textureCount = 1;
  15029. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15030. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15031. var types = new Array();
  15032. var samplingModes = new Array();
  15033. if (options !== undefined) {
  15034. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15035. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15036. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15037. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15038. textureCount = options.textureCount || 1;
  15039. if (options.types) {
  15040. types = options.types;
  15041. }
  15042. if (options.samplingModes) {
  15043. samplingModes = options.samplingModes;
  15044. }
  15045. }
  15046. var gl = this._gl;
  15047. // Create the framebuffer
  15048. var framebuffer = gl.createFramebuffer();
  15049. this.bindUnboundFramebuffer(framebuffer);
  15050. var width = size.width || size;
  15051. var height = size.height || size;
  15052. var textures = [];
  15053. var attachments = [];
  15054. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15055. for (var i = 0; i < textureCount; i++) {
  15056. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15057. var type = types[i] || defaultType;
  15058. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15059. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15060. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15061. }
  15062. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15063. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15064. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15065. }
  15066. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15067. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15068. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15069. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15070. }
  15071. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15072. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15073. textures.push(texture);
  15074. attachments.push(attachment);
  15075. gl.activeTexture(gl["TEXTURE" + i]);
  15076. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15081. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15082. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15083. if (generateMipMaps) {
  15084. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15085. }
  15086. // Unbind
  15087. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15088. texture._framebuffer = framebuffer;
  15089. texture._depthStencilBuffer = depthStencilBuffer;
  15090. texture.baseWidth = width;
  15091. texture.baseHeight = height;
  15092. texture.width = width;
  15093. texture.height = height;
  15094. texture.isReady = true;
  15095. texture.samples = 1;
  15096. texture.generateMipMaps = generateMipMaps;
  15097. texture.samplingMode = samplingMode;
  15098. texture.type = type;
  15099. texture._generateDepthBuffer = generateDepthBuffer;
  15100. texture._generateStencilBuffer = generateStencilBuffer;
  15101. texture._attachments = attachments;
  15102. this._internalTexturesCache.push(texture);
  15103. }
  15104. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15105. // Depth texture
  15106. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15107. gl.activeTexture(gl.TEXTURE0);
  15108. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15110. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15113. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  15114. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15115. depthTexture._framebuffer = framebuffer;
  15116. depthTexture.baseWidth = width;
  15117. depthTexture.baseHeight = height;
  15118. depthTexture.width = width;
  15119. depthTexture.height = height;
  15120. depthTexture.isReady = true;
  15121. depthTexture.samples = 1;
  15122. depthTexture.generateMipMaps = generateMipMaps;
  15123. depthTexture.samplingMode = gl.NEAREST;
  15124. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15125. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15126. textures.push(depthTexture);
  15127. this._internalTexturesCache.push(depthTexture);
  15128. }
  15129. gl.drawBuffers(attachments);
  15130. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15131. this.bindUnboundFramebuffer(null);
  15132. this.resetTextureCache();
  15133. return textures;
  15134. };
  15135. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15136. if (samples === void 0) { samples = 1; }
  15137. var depthStencilBuffer = null;
  15138. var gl = this._gl;
  15139. // Create the depth/stencil buffer
  15140. if (generateStencilBuffer) {
  15141. depthStencilBuffer = gl.createRenderbuffer();
  15142. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15143. if (samples > 1) {
  15144. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15145. }
  15146. else {
  15147. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15148. }
  15149. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15150. }
  15151. else if (generateDepthBuffer) {
  15152. depthStencilBuffer = gl.createRenderbuffer();
  15153. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15154. if (samples > 1) {
  15155. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15156. }
  15157. else {
  15158. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15159. }
  15160. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15161. }
  15162. return depthStencilBuffer;
  15163. };
  15164. /**
  15165. * Updates the sample count of a render target texture
  15166. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15167. * @param texture defines the texture to update
  15168. * @param samples defines the sample count to set
  15169. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15170. */
  15171. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15172. if (this.webGLVersion < 2 || !texture) {
  15173. return 1;
  15174. }
  15175. if (texture.samples === samples) {
  15176. return samples;
  15177. }
  15178. var gl = this._gl;
  15179. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15180. // Dispose previous render buffers
  15181. if (texture._depthStencilBuffer) {
  15182. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15183. texture._depthStencilBuffer = null;
  15184. }
  15185. if (texture._MSAAFramebuffer) {
  15186. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15187. texture._MSAAFramebuffer = null;
  15188. }
  15189. if (texture._MSAARenderBuffer) {
  15190. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15191. texture._MSAARenderBuffer = null;
  15192. }
  15193. if (samples > 1) {
  15194. var framebuffer = gl.createFramebuffer();
  15195. if (!framebuffer) {
  15196. throw new Error("Unable to create multi sampled framebuffer");
  15197. }
  15198. texture._MSAAFramebuffer = framebuffer;
  15199. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15200. var colorRenderbuffer = gl.createRenderbuffer();
  15201. if (!colorRenderbuffer) {
  15202. throw new Error("Unable to create multi sampled framebuffer");
  15203. }
  15204. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15205. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15206. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15207. texture._MSAARenderBuffer = colorRenderbuffer;
  15208. }
  15209. else {
  15210. this.bindUnboundFramebuffer(texture._framebuffer);
  15211. }
  15212. texture.samples = samples;
  15213. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15214. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15215. this.bindUnboundFramebuffer(null);
  15216. return samples;
  15217. };
  15218. /**
  15219. * Update the sample count for a given multiple render target texture
  15220. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15221. * @param textures defines the textures to update
  15222. * @param samples defines the sample count to set
  15223. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15224. */
  15225. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15226. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15227. return 1;
  15228. }
  15229. if (textures[0].samples === samples) {
  15230. return samples;
  15231. }
  15232. var gl = this._gl;
  15233. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15234. // Dispose previous render buffers
  15235. if (textures[0]._depthStencilBuffer) {
  15236. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15237. textures[0]._depthStencilBuffer = null;
  15238. }
  15239. if (textures[0]._MSAAFramebuffer) {
  15240. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15241. textures[0]._MSAAFramebuffer = null;
  15242. }
  15243. for (var i = 0; i < textures.length; i++) {
  15244. if (textures[i]._MSAARenderBuffer) {
  15245. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15246. textures[i]._MSAARenderBuffer = null;
  15247. }
  15248. }
  15249. if (samples > 1) {
  15250. var framebuffer = gl.createFramebuffer();
  15251. if (!framebuffer) {
  15252. throw new Error("Unable to create multi sampled framebuffer");
  15253. }
  15254. this.bindUnboundFramebuffer(framebuffer);
  15255. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15256. var attachments = [];
  15257. for (var i = 0; i < textures.length; i++) {
  15258. var texture = textures[i];
  15259. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15260. var colorRenderbuffer = gl.createRenderbuffer();
  15261. if (!colorRenderbuffer) {
  15262. throw new Error("Unable to create multi sampled framebuffer");
  15263. }
  15264. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15265. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15266. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15267. texture._MSAAFramebuffer = framebuffer;
  15268. texture._MSAARenderBuffer = colorRenderbuffer;
  15269. texture.samples = samples;
  15270. texture._depthStencilBuffer = depthStencilBuffer;
  15271. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15272. attachments.push(attachment);
  15273. }
  15274. gl.drawBuffers(attachments);
  15275. }
  15276. else {
  15277. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15278. }
  15279. this.bindUnboundFramebuffer(null);
  15280. return samples;
  15281. };
  15282. /** @hidden */
  15283. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15284. if (faceIndex === void 0) { faceIndex = 0; }
  15285. if (lod === void 0) { lod = 0; }
  15286. var gl = this._gl;
  15287. var target = gl.TEXTURE_2D;
  15288. if (texture.isCube) {
  15289. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15290. }
  15291. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15292. };
  15293. /** @hidden */
  15294. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15295. if (faceIndex === void 0) { faceIndex = 0; }
  15296. if (lod === void 0) { lod = 0; }
  15297. var gl = this._gl;
  15298. var textureType = this._getWebGLTextureType(texture.type);
  15299. var format = this._getInternalFormat(texture.format);
  15300. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15301. this._unpackFlipY(texture.invertY);
  15302. var target = gl.TEXTURE_2D;
  15303. if (texture.isCube) {
  15304. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15305. }
  15306. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15307. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15308. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15309. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15310. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15311. };
  15312. /** @hidden */
  15313. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15314. if (faceIndex === void 0) { faceIndex = 0; }
  15315. if (lod === void 0) { lod = 0; }
  15316. var gl = this._gl;
  15317. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15318. this._bindTextureDirectly(bindTarget, texture, true);
  15319. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15320. this._bindTextureDirectly(bindTarget, null, true);
  15321. };
  15322. /** @hidden */
  15323. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15324. if (faceIndex === void 0) { faceIndex = 0; }
  15325. if (lod === void 0) { lod = 0; }
  15326. var gl = this._gl;
  15327. var textureType = this._getWebGLTextureType(texture.type);
  15328. var format = this._getInternalFormat(texture.format);
  15329. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15330. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15331. this._bindTextureDirectly(bindTarget, texture, true);
  15332. this._unpackFlipY(texture.invertY);
  15333. var target = gl.TEXTURE_2D;
  15334. if (texture.isCube) {
  15335. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15336. }
  15337. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15338. this._bindTextureDirectly(bindTarget, null, true);
  15339. };
  15340. /**
  15341. * Creates a new render target cube texture
  15342. * @param size defines the size of the texture
  15343. * @param options defines the options used to create the texture
  15344. * @returns a new render target cube texture stored in an InternalTexture
  15345. */
  15346. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15347. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15348. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15349. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15350. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15351. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15352. }
  15353. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15354. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15355. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15356. }
  15357. var gl = this._gl;
  15358. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15359. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15360. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15361. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15362. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15363. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15364. }
  15365. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15368. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15369. for (var face = 0; face < 6; face++) {
  15370. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15371. }
  15372. // Create the framebuffer
  15373. var framebuffer = gl.createFramebuffer();
  15374. this.bindUnboundFramebuffer(framebuffer);
  15375. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15376. // MipMaps
  15377. if (fullOptions.generateMipMaps) {
  15378. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15379. }
  15380. // Unbind
  15381. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15382. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15383. this.bindUnboundFramebuffer(null);
  15384. texture._framebuffer = framebuffer;
  15385. texture.width = size;
  15386. texture.height = size;
  15387. texture.isReady = true;
  15388. texture.isCube = true;
  15389. texture.samples = 1;
  15390. texture.generateMipMaps = fullOptions.generateMipMaps;
  15391. texture.samplingMode = fullOptions.samplingMode;
  15392. texture.type = fullOptions.type;
  15393. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15394. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15395. this._internalTexturesCache.push(texture);
  15396. return texture;
  15397. };
  15398. /**
  15399. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15400. * @param rootUrl defines the url where the file to load is located
  15401. * @param scene defines the current scene
  15402. * @param lodScale defines scale to apply to the mip map selection
  15403. * @param lodOffset defines offset to apply to the mip map selection
  15404. * @param onLoad defines an optional callback raised when the texture is loaded
  15405. * @param onError defines an optional callback raised if there is an issue to load the texture
  15406. * @param format defines the format of the data
  15407. * @param forcedExtension defines the extension to use to pick the right loader
  15408. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15409. * @returns the cube texture as an InternalTexture
  15410. */
  15411. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15412. var _this = this;
  15413. if (onLoad === void 0) { onLoad = null; }
  15414. if (onError === void 0) { onError = null; }
  15415. if (forcedExtension === void 0) { forcedExtension = null; }
  15416. if (createPolynomials === void 0) { createPolynomials = true; }
  15417. var callback = function (loadData) {
  15418. if (!loadData) {
  15419. if (onLoad) {
  15420. onLoad(null);
  15421. }
  15422. return;
  15423. }
  15424. var texture = loadData.texture;
  15425. if (!createPolynomials) {
  15426. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15427. }
  15428. else if (loadData.info.sphericalPolynomial) {
  15429. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15430. }
  15431. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15432. if (_this._caps.textureLOD) {
  15433. // Do not add extra process if texture lod is supported.
  15434. if (onLoad) {
  15435. onLoad(texture);
  15436. }
  15437. return;
  15438. }
  15439. var mipSlices = 3;
  15440. var gl = _this._gl;
  15441. var width = loadData.width;
  15442. if (!width) {
  15443. return;
  15444. }
  15445. var textures = [];
  15446. for (var i = 0; i < mipSlices; i++) {
  15447. //compute LOD from even spacing in smoothness (matching shader calculation)
  15448. var smoothness = i / (mipSlices - 1);
  15449. var roughness = 1 - smoothness;
  15450. var minLODIndex = lodOffset; // roughness = 0
  15451. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15452. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15453. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15454. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15455. glTextureFromLod.isCube = true;
  15456. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15457. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15458. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15461. if (loadData.isDDS) {
  15462. var info = loadData.info;
  15463. var data = loadData.data;
  15464. _this._unpackFlipY(info.isCompressed);
  15465. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, true, 6, mipmapIndex);
  15466. }
  15467. else {
  15468. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15469. }
  15470. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15471. // Wrap in a base texture for easy binding.
  15472. var lodTexture = new BABYLON.BaseTexture(scene);
  15473. lodTexture.isCube = true;
  15474. lodTexture._texture = glTextureFromLod;
  15475. glTextureFromLod.isReady = true;
  15476. textures.push(lodTexture);
  15477. }
  15478. texture._lodTextureHigh = textures[2];
  15479. texture._lodTextureMid = textures[1];
  15480. texture._lodTextureLow = textures[0];
  15481. if (onLoad) {
  15482. onLoad(texture);
  15483. }
  15484. };
  15485. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15486. };
  15487. /**
  15488. * Creates a cube texture
  15489. * @param rootUrl defines the url where the files to load is located
  15490. * @param scene defines the current scene
  15491. * @param files defines the list of files to load (1 per face)
  15492. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15493. * @param onLoad defines an optional callback raised when the texture is loaded
  15494. * @param onError defines an optional callback raised if there is an issue to load the texture
  15495. * @param format defines the format of the data
  15496. * @param forcedExtension defines the extension to use to pick the right loader
  15497. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15498. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15499. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15500. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15501. * @returns the cube texture as an InternalTexture
  15502. */
  15503. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15504. var _this = this;
  15505. if (onLoad === void 0) { onLoad = null; }
  15506. if (onError === void 0) { onError = null; }
  15507. if (forcedExtension === void 0) { forcedExtension = null; }
  15508. if (createPolynomials === void 0) { createPolynomials = false; }
  15509. if (lodScale === void 0) { lodScale = 0; }
  15510. if (lodOffset === void 0) { lodOffset = 0; }
  15511. if (fallback === void 0) { fallback = null; }
  15512. var gl = this._gl;
  15513. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15514. texture.isCube = true;
  15515. texture.url = rootUrl;
  15516. texture.generateMipMaps = !noMipmap;
  15517. texture._lodGenerationScale = lodScale;
  15518. texture._lodGenerationOffset = lodOffset;
  15519. if (!this._doNotHandleContextLost) {
  15520. texture._extension = forcedExtension;
  15521. texture._files = files;
  15522. }
  15523. var lastDot = rootUrl.lastIndexOf('.');
  15524. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15525. var loader = null;
  15526. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15527. var availableLoader = _a[_i];
  15528. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15529. loader = availableLoader;
  15530. break;
  15531. }
  15532. }
  15533. var onInternalError = function (request, exception) {
  15534. if (loader) {
  15535. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15536. if (fallbackUrl) {
  15537. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15538. }
  15539. }
  15540. if (onError && request) {
  15541. onError(request.status + " " + request.statusText, exception);
  15542. }
  15543. };
  15544. if (loader) {
  15545. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15546. var onloaddata = function (data) {
  15547. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15548. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15549. };
  15550. if (files && files.length === 6) {
  15551. if (loader.supportCascades) {
  15552. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15553. }
  15554. else if (onError) {
  15555. onError("Textures type does not support cascades.");
  15556. }
  15557. }
  15558. else {
  15559. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15560. }
  15561. }
  15562. else {
  15563. if (!files) {
  15564. throw new Error("Cannot load cubemap because files were not defined");
  15565. }
  15566. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15567. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15568. var height = width;
  15569. _this._prepareWorkingCanvas();
  15570. if (!_this._workingCanvas || !_this._workingContext) {
  15571. return;
  15572. }
  15573. _this._workingCanvas.width = width;
  15574. _this._workingCanvas.height = height;
  15575. var faces = [
  15576. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15577. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15578. ];
  15579. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15580. _this._unpackFlipY(false);
  15581. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15582. for (var index = 0; index < faces.length; index++) {
  15583. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15584. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15585. }
  15586. if (!noMipmap) {
  15587. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15588. }
  15589. _this._setCubeMapTextureParams(!noMipmap);
  15590. texture.width = width;
  15591. texture.height = height;
  15592. texture.isReady = true;
  15593. if (format) {
  15594. texture.format = format;
  15595. }
  15596. texture.onLoadedObservable.notifyObservers(texture);
  15597. texture.onLoadedObservable.clear();
  15598. if (onLoad) {
  15599. onLoad();
  15600. }
  15601. }, files, onError);
  15602. }
  15603. this._internalTexturesCache.push(texture);
  15604. return texture;
  15605. };
  15606. /**
  15607. * @hidden
  15608. */
  15609. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15610. var gl = this._gl;
  15611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15615. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15616. // this.resetTextureCache();
  15617. };
  15618. /**
  15619. * Update a raw cube texture
  15620. * @param texture defines the texture to udpdate
  15621. * @param data defines the data to store
  15622. * @param format defines the data format
  15623. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15624. * @param invertY defines if data must be stored with Y axis inverted
  15625. * @param compression defines the compression used (null by default)
  15626. * @param level defines which level of the texture to update
  15627. */
  15628. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15629. if (compression === void 0) { compression = null; }
  15630. if (level === void 0) { level = 0; }
  15631. texture._bufferViewArray = data;
  15632. texture.format = format;
  15633. texture.type = type;
  15634. texture.invertY = invertY;
  15635. texture._compression = compression;
  15636. var gl = this._gl;
  15637. var textureType = this._getWebGLTextureType(type);
  15638. var internalFormat = this._getInternalFormat(format);
  15639. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15640. var needConversion = false;
  15641. if (internalFormat === gl.RGB) {
  15642. internalFormat = gl.RGBA;
  15643. needConversion = true;
  15644. }
  15645. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15646. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15647. if (texture.width % 4 !== 0) {
  15648. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15649. }
  15650. // Data are known to be in +X +Y +Z -X -Y -Z
  15651. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15652. var faceData = data[faceIndex];
  15653. if (compression) {
  15654. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15655. }
  15656. else {
  15657. if (needConversion) {
  15658. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15659. }
  15660. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15661. }
  15662. }
  15663. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15664. if (isPot && texture.generateMipMaps && level === 0) {
  15665. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15666. }
  15667. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15668. // this.resetTextureCache();
  15669. texture.isReady = true;
  15670. };
  15671. /**
  15672. * Creates a new raw cube texture
  15673. * @param data defines the array of data to use to create each face
  15674. * @param size defines the size of the textures
  15675. * @param format defines the format of the data
  15676. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15677. * @param generateMipMaps defines if the engine should generate the mip levels
  15678. * @param invertY defines if data must be stored with Y axis inverted
  15679. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15680. * @param compression defines the compression used (null by default)
  15681. * @returns the cube texture as an InternalTexture
  15682. */
  15683. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15684. if (compression === void 0) { compression = null; }
  15685. var gl = this._gl;
  15686. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15687. texture.isCube = true;
  15688. texture.format = format;
  15689. texture.type = type;
  15690. if (!this._doNotHandleContextLost) {
  15691. texture._bufferViewArray = data;
  15692. }
  15693. var textureType = this._getWebGLTextureType(type);
  15694. var internalFormat = this._getInternalFormat(format);
  15695. if (internalFormat === gl.RGB) {
  15696. internalFormat = gl.RGBA;
  15697. }
  15698. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15699. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15700. generateMipMaps = false;
  15701. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15702. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15703. }
  15704. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15705. generateMipMaps = false;
  15706. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15707. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15708. }
  15709. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15710. generateMipMaps = false;
  15711. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15712. }
  15713. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15714. generateMipMaps = false;
  15715. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15716. }
  15717. var width = size;
  15718. var height = width;
  15719. texture.width = width;
  15720. texture.height = height;
  15721. // Double check on POT to generate Mips.
  15722. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15723. if (!isPot) {
  15724. generateMipMaps = false;
  15725. }
  15726. // Upload data if needed. The texture won't be ready until then.
  15727. if (data) {
  15728. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15729. }
  15730. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15731. // Filters
  15732. if (data && generateMipMaps) {
  15733. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15734. }
  15735. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15738. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15739. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15740. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15741. texture.generateMipMaps = generateMipMaps;
  15742. return texture;
  15743. };
  15744. /**
  15745. * Creates a new raw cube texture from a specified url
  15746. * @param url defines the url where the data is located
  15747. * @param scene defines the current scene
  15748. * @param size defines the size of the textures
  15749. * @param format defines the format of the data
  15750. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15751. * @param noMipmap defines if the engine should avoid generating the mip levels
  15752. * @param callback defines a callback used to extract texture data from loaded data
  15753. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15754. * @param onLoad defines a callback called when texture is loaded
  15755. * @param onError defines a callback called if there is an error
  15756. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15757. * @param invertY defines if data must be stored with Y axis inverted
  15758. * @returns the cube texture as an InternalTexture
  15759. */
  15760. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15761. var _this = this;
  15762. if (onLoad === void 0) { onLoad = null; }
  15763. if (onError === void 0) { onError = null; }
  15764. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15765. if (invertY === void 0) { invertY = false; }
  15766. var gl = this._gl;
  15767. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15768. scene._addPendingData(texture);
  15769. texture.url = url;
  15770. this._internalTexturesCache.push(texture);
  15771. var onerror = function (request, exception) {
  15772. scene._removePendingData(texture);
  15773. if (onError && request) {
  15774. onError(request.status + " " + request.statusText, exception);
  15775. }
  15776. };
  15777. var internalCallback = function (data) {
  15778. var width = texture.width;
  15779. var faceDataArrays = callback(data);
  15780. if (!faceDataArrays) {
  15781. return;
  15782. }
  15783. if (mipmapGenerator) {
  15784. var textureType = _this._getWebGLTextureType(type);
  15785. var internalFormat = _this._getInternalFormat(format);
  15786. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15787. var needConversion = false;
  15788. if (internalFormat === gl.RGB) {
  15789. internalFormat = gl.RGBA;
  15790. needConversion = true;
  15791. }
  15792. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15793. _this._unpackFlipY(false);
  15794. var mipData = mipmapGenerator(faceDataArrays);
  15795. for (var level = 0; level < mipData.length; level++) {
  15796. var mipSize = width >> level;
  15797. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15798. var mipFaceData = mipData[level][faceIndex];
  15799. if (needConversion) {
  15800. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15801. }
  15802. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15803. }
  15804. }
  15805. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15806. }
  15807. else {
  15808. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15809. }
  15810. texture.isReady = true;
  15811. // this.resetTextureCache();
  15812. scene._removePendingData(texture);
  15813. if (onLoad) {
  15814. onLoad();
  15815. }
  15816. };
  15817. this._loadFile(url, function (data) {
  15818. internalCallback(data);
  15819. }, undefined, scene.database, true, onerror);
  15820. return texture;
  15821. };
  15822. ;
  15823. /**
  15824. * Update a raw 3D texture
  15825. * @param texture defines the texture to update
  15826. * @param data defines the data to store
  15827. * @param format defines the data format
  15828. * @param invertY defines if data must be stored with Y axis inverted
  15829. * @param compression defines the used compression (can be null)
  15830. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15831. */
  15832. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15833. if (compression === void 0) { compression = null; }
  15834. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15835. var internalType = this._getWebGLTextureType(textureType);
  15836. var internalFormat = this._getInternalFormat(format);
  15837. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15838. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15839. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15840. if (!this._doNotHandleContextLost) {
  15841. texture._bufferView = data;
  15842. texture.format = format;
  15843. texture.invertY = invertY;
  15844. texture._compression = compression;
  15845. }
  15846. if (texture.width % 4 !== 0) {
  15847. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15848. }
  15849. if (compression && data) {
  15850. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15851. }
  15852. else {
  15853. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15854. }
  15855. if (texture.generateMipMaps) {
  15856. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15857. }
  15858. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15859. // this.resetTextureCache();
  15860. texture.isReady = true;
  15861. };
  15862. /**
  15863. * Creates a new raw 3D texture
  15864. * @param data defines the data used to create the texture
  15865. * @param width defines the width of the texture
  15866. * @param height defines the height of the texture
  15867. * @param depth defines the depth of the texture
  15868. * @param format defines the format of the texture
  15869. * @param generateMipMaps defines if the engine must generate mip levels
  15870. * @param invertY defines if data must be stored with Y axis inverted
  15871. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15872. * @param compression defines the compressed used (can be null)
  15873. * @param textureType defines the compressed used (can be null)
  15874. * @returns a new raw 3D texture (stored in an InternalTexture)
  15875. */
  15876. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15877. if (compression === void 0) { compression = null; }
  15878. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15879. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15880. texture.baseWidth = width;
  15881. texture.baseHeight = height;
  15882. texture.baseDepth = depth;
  15883. texture.width = width;
  15884. texture.height = height;
  15885. texture.depth = depth;
  15886. texture.format = format;
  15887. texture.type = textureType;
  15888. texture.generateMipMaps = generateMipMaps;
  15889. texture.samplingMode = samplingMode;
  15890. texture.is3D = true;
  15891. if (!this._doNotHandleContextLost) {
  15892. texture._bufferView = data;
  15893. }
  15894. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15895. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15896. // Filters
  15897. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15898. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15899. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15900. if (generateMipMaps) {
  15901. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15902. }
  15903. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15904. this._internalTexturesCache.push(texture);
  15905. return texture;
  15906. };
  15907. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15908. var gl = this._gl;
  15909. if (!gl) {
  15910. return;
  15911. }
  15912. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15914. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15915. if (!noMipmap && !isCompressed) {
  15916. gl.generateMipmap(gl.TEXTURE_2D);
  15917. }
  15918. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15919. // this.resetTextureCache();
  15920. if (scene) {
  15921. scene._removePendingData(texture);
  15922. }
  15923. texture.onLoadedObservable.notifyObservers(texture);
  15924. texture.onLoadedObservable.clear();
  15925. };
  15926. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15927. var _this = this;
  15928. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15929. var maxTextureSize = this.getCaps().maxTextureSize;
  15930. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  15931. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  15932. var gl = this._gl;
  15933. if (!gl) {
  15934. return;
  15935. }
  15936. if (!texture._webGLTexture) {
  15937. // this.resetTextureCache();
  15938. if (scene) {
  15939. scene._removePendingData(texture);
  15940. }
  15941. return;
  15942. }
  15943. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15944. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15945. texture.baseWidth = width;
  15946. texture.baseHeight = height;
  15947. texture.width = potWidth;
  15948. texture.height = potHeight;
  15949. texture.isReady = true;
  15950. if (processFunction(potWidth, potHeight, function () {
  15951. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15952. })) {
  15953. // Returning as texture needs extra async steps
  15954. return;
  15955. }
  15956. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15957. };
  15958. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15959. // Create new RGBA data container.
  15960. var rgbaData;
  15961. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15962. rgbaData = new Float32Array(width * height * 4);
  15963. }
  15964. else {
  15965. rgbaData = new Uint32Array(width * height * 4);
  15966. }
  15967. // Convert each pixel.
  15968. for (var x = 0; x < width; x++) {
  15969. for (var y = 0; y < height; y++) {
  15970. var index = (y * width + x) * 3;
  15971. var newIndex = (y * width + x) * 4;
  15972. // Map Old Value to new value.
  15973. rgbaData[newIndex + 0] = rgbData[index + 0];
  15974. rgbaData[newIndex + 1] = rgbData[index + 1];
  15975. rgbaData[newIndex + 2] = rgbData[index + 2];
  15976. // Add fully opaque alpha channel.
  15977. rgbaData[newIndex + 3] = 1;
  15978. }
  15979. }
  15980. return rgbaData;
  15981. };
  15982. /** @hidden */
  15983. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15984. var gl = this._gl;
  15985. if (texture._framebuffer) {
  15986. gl.deleteFramebuffer(texture._framebuffer);
  15987. texture._framebuffer = null;
  15988. }
  15989. if (texture._depthStencilBuffer) {
  15990. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15991. texture._depthStencilBuffer = null;
  15992. }
  15993. if (texture._MSAAFramebuffer) {
  15994. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15995. texture._MSAAFramebuffer = null;
  15996. }
  15997. if (texture._MSAARenderBuffer) {
  15998. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15999. texture._MSAARenderBuffer = null;
  16000. }
  16001. };
  16002. /** @hidden */
  16003. Engine.prototype._releaseTexture = function (texture) {
  16004. var gl = this._gl;
  16005. this._releaseFramebufferObjects(texture);
  16006. gl.deleteTexture(texture._webGLTexture);
  16007. // Unbind channels
  16008. this.unbindAllTextures();
  16009. var index = this._internalTexturesCache.indexOf(texture);
  16010. if (index !== -1) {
  16011. this._internalTexturesCache.splice(index, 1);
  16012. }
  16013. // Integrated fixed lod samplers.
  16014. if (texture._lodTextureHigh) {
  16015. texture._lodTextureHigh.dispose();
  16016. }
  16017. if (texture._lodTextureMid) {
  16018. texture._lodTextureMid.dispose();
  16019. }
  16020. if (texture._lodTextureLow) {
  16021. texture._lodTextureLow.dispose();
  16022. }
  16023. // Set output texture of post process to null if the texture has been released/disposed
  16024. this.scenes.forEach(function (scene) {
  16025. scene.postProcesses.forEach(function (postProcess) {
  16026. if (postProcess._outputTexture == texture) {
  16027. postProcess._outputTexture = null;
  16028. }
  16029. });
  16030. scene.cameras.forEach(function (camera) {
  16031. camera._postProcesses.forEach(function (postProcess) {
  16032. if (postProcess) {
  16033. if (postProcess._outputTexture == texture) {
  16034. postProcess._outputTexture = null;
  16035. }
  16036. }
  16037. });
  16038. });
  16039. });
  16040. };
  16041. Engine.prototype.setProgram = function (program) {
  16042. if (this._currentProgram !== program) {
  16043. this._gl.useProgram(program);
  16044. this._currentProgram = program;
  16045. }
  16046. };
  16047. /**
  16048. * Binds an effect to the webGL context
  16049. * @param effect defines the effect to bind
  16050. */
  16051. Engine.prototype.bindSamplers = function (effect) {
  16052. this.setProgram(effect.getProgram());
  16053. var samplers = effect.getSamplers();
  16054. for (var index = 0; index < samplers.length; index++) {
  16055. var uniform = effect.getUniform(samplers[index]);
  16056. if (uniform) {
  16057. this._boundUniforms[index] = uniform;
  16058. }
  16059. }
  16060. this._currentEffect = null;
  16061. };
  16062. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16063. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16064. return;
  16065. }
  16066. // Remove
  16067. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16068. // Bind last to it
  16069. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16070. // Bind to dummy
  16071. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16072. };
  16073. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16074. if (!internalTexture) {
  16075. return -1;
  16076. }
  16077. internalTexture._initialSlot = channel;
  16078. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16079. if (channel !== internalTexture._designatedSlot) {
  16080. this._textureCollisions.addCount(1, false);
  16081. }
  16082. }
  16083. else {
  16084. if (channel !== internalTexture._designatedSlot) {
  16085. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16086. return internalTexture._designatedSlot;
  16087. }
  16088. else {
  16089. // No slot for this texture, let's pick a new one (if we find a free slot)
  16090. if (this._nextFreeTextureSlots.length) {
  16091. return this._nextFreeTextureSlots[0];
  16092. }
  16093. // We need to recycle the oldest bound texture, sorry.
  16094. this._textureCollisions.addCount(1, false);
  16095. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16096. }
  16097. }
  16098. }
  16099. return channel;
  16100. };
  16101. Engine.prototype._linkTrackers = function (previous, next) {
  16102. previous.next = next;
  16103. next.previous = previous;
  16104. };
  16105. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16106. var currentSlot = internalTexture._designatedSlot;
  16107. if (currentSlot === -1) {
  16108. return -1;
  16109. }
  16110. internalTexture._designatedSlot = -1;
  16111. if (this.disableTextureBindingOptimization) {
  16112. return -1;
  16113. }
  16114. // Remove from bound list
  16115. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16116. // Free the slot
  16117. this._boundTexturesCache[currentSlot] = null;
  16118. this._nextFreeTextureSlots.push(currentSlot);
  16119. return currentSlot;
  16120. };
  16121. Engine.prototype._activateCurrentTexture = function () {
  16122. if (this._currentTextureChannel !== this._activeChannel) {
  16123. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16124. this._currentTextureChannel = this._activeChannel;
  16125. }
  16126. };
  16127. /** @hidden */
  16128. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16129. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16130. if (force === void 0) { force = false; }
  16131. var wasPreviouslyBound = false;
  16132. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16133. this._activeChannel = texture._designatedSlot;
  16134. }
  16135. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16136. var isTextureForRendering = texture && texture._initialSlot > -1;
  16137. if (currentTextureBound !== texture || force) {
  16138. if (currentTextureBound) {
  16139. this._removeDesignatedSlot(currentTextureBound);
  16140. }
  16141. this._activateCurrentTexture();
  16142. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16143. this._boundTexturesCache[this._activeChannel] = texture;
  16144. if (texture) {
  16145. if (!this.disableTextureBindingOptimization) {
  16146. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16147. if (slotIndex > -1) {
  16148. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16149. }
  16150. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16151. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16152. }
  16153. texture._designatedSlot = this._activeChannel;
  16154. }
  16155. }
  16156. else if (forTextureDataUpdate) {
  16157. wasPreviouslyBound = true;
  16158. this._activateCurrentTexture();
  16159. }
  16160. if (isTextureForRendering && !forTextureDataUpdate) {
  16161. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16162. }
  16163. return wasPreviouslyBound;
  16164. };
  16165. /** @hidden */
  16166. Engine.prototype._bindTexture = function (channel, texture) {
  16167. if (channel < 0) {
  16168. return;
  16169. }
  16170. if (texture) {
  16171. channel = this._getCorrectTextureChannel(channel, texture);
  16172. }
  16173. this._activeChannel = channel;
  16174. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16175. };
  16176. /**
  16177. * Sets a texture to the webGL context from a postprocess
  16178. * @param channel defines the channel to use
  16179. * @param postProcess defines the source postprocess
  16180. */
  16181. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16182. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16183. };
  16184. /**
  16185. * Binds the output of the passed in post process to the texture channel specified
  16186. * @param channel The channel the texture should be bound to
  16187. * @param postProcess The post process which's output should be bound
  16188. */
  16189. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16190. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16191. };
  16192. /**
  16193. * Unbind all textures from the webGL context
  16194. */
  16195. Engine.prototype.unbindAllTextures = function () {
  16196. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16197. this._activeChannel = channel;
  16198. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16199. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16200. if (this.webGLVersion > 1) {
  16201. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16202. }
  16203. }
  16204. };
  16205. /**
  16206. * Sets a texture to the according uniform.
  16207. * @param channel The texture channel
  16208. * @param uniform The uniform to set
  16209. * @param texture The texture to apply
  16210. */
  16211. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16212. if (channel < 0) {
  16213. return;
  16214. }
  16215. if (uniform) {
  16216. this._boundUniforms[channel] = uniform;
  16217. }
  16218. this._setTexture(channel, texture);
  16219. };
  16220. /**
  16221. * Sets a depth stencil texture from a render target to the according uniform.
  16222. * @param channel The texture channel
  16223. * @param uniform The uniform to set
  16224. * @param texture The render target texture containing the depth stencil texture to apply
  16225. */
  16226. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16227. if (channel < 0) {
  16228. return;
  16229. }
  16230. if (uniform) {
  16231. this._boundUniforms[channel] = uniform;
  16232. }
  16233. if (!texture || !texture.depthStencilTexture) {
  16234. this._setTexture(channel, null);
  16235. }
  16236. else {
  16237. this._setTexture(channel, texture, false, true);
  16238. }
  16239. };
  16240. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16241. var uniform = this._boundUniforms[sourceSlot];
  16242. if (uniform._currentState === destination) {
  16243. return;
  16244. }
  16245. this._gl.uniform1i(uniform, destination);
  16246. uniform._currentState = destination;
  16247. };
  16248. Engine.prototype._getTextureWrapMode = function (mode) {
  16249. switch (mode) {
  16250. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16251. return this._gl.REPEAT;
  16252. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16253. return this._gl.CLAMP_TO_EDGE;
  16254. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16255. return this._gl.MIRRORED_REPEAT;
  16256. }
  16257. return this._gl.REPEAT;
  16258. };
  16259. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16260. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16261. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16262. // Not ready?
  16263. if (!texture) {
  16264. if (this._boundTexturesCache[channel] != null) {
  16265. this._activeChannel = channel;
  16266. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16267. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16268. if (this.webGLVersion > 1) {
  16269. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16270. }
  16271. }
  16272. return false;
  16273. }
  16274. // Video
  16275. if (texture.video) {
  16276. this._activeChannel = channel;
  16277. texture.update();
  16278. }
  16279. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16280. texture.delayLoad();
  16281. return false;
  16282. }
  16283. var internalTexture;
  16284. if (depthStencilTexture) {
  16285. internalTexture = texture.depthStencilTexture;
  16286. }
  16287. else if (texture.isReady()) {
  16288. internalTexture = texture.getInternalTexture();
  16289. }
  16290. else if (texture.isCube) {
  16291. internalTexture = this.emptyCubeTexture;
  16292. }
  16293. else if (texture.is3D) {
  16294. internalTexture = this.emptyTexture3D;
  16295. }
  16296. else {
  16297. internalTexture = this.emptyTexture;
  16298. }
  16299. if (!isPartOfTextureArray) {
  16300. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16301. }
  16302. var needToBind = true;
  16303. if (this._boundTexturesCache[channel] === internalTexture) {
  16304. this._moveBoundTextureOnTop(internalTexture);
  16305. if (!isPartOfTextureArray) {
  16306. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16307. }
  16308. needToBind = false;
  16309. }
  16310. this._activeChannel = channel;
  16311. if (internalTexture && internalTexture.is3D) {
  16312. if (needToBind) {
  16313. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16314. }
  16315. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16316. internalTexture._cachedWrapU = texture.wrapU;
  16317. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16318. }
  16319. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16320. internalTexture._cachedWrapV = texture.wrapV;
  16321. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16322. }
  16323. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16324. internalTexture._cachedWrapR = texture.wrapR;
  16325. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16326. }
  16327. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16328. }
  16329. else if (internalTexture && internalTexture.isCube) {
  16330. if (needToBind) {
  16331. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16332. }
  16333. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16334. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16335. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16336. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16337. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16338. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16339. }
  16340. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16341. }
  16342. else {
  16343. if (needToBind) {
  16344. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16345. }
  16346. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16347. internalTexture._cachedWrapU = texture.wrapU;
  16348. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16349. }
  16350. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16351. internalTexture._cachedWrapV = texture.wrapV;
  16352. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16353. }
  16354. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16355. }
  16356. return true;
  16357. };
  16358. /**
  16359. * Sets an array of texture to the webGL context
  16360. * @param channel defines the channel where the texture array must be set
  16361. * @param uniform defines the associated uniform location
  16362. * @param textures defines the array of textures to bind
  16363. */
  16364. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16365. if (channel < 0 || !uniform) {
  16366. return;
  16367. }
  16368. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16369. this._textureUnits = new Int32Array(textures.length);
  16370. }
  16371. for (var i = 0; i < textures.length; i++) {
  16372. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16373. }
  16374. this._gl.uniform1iv(uniform, this._textureUnits);
  16375. for (var index = 0; index < textures.length; index++) {
  16376. this._setTexture(this._textureUnits[index], textures[index], true);
  16377. }
  16378. };
  16379. /** @hidden */
  16380. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16381. var internalTexture = texture.getInternalTexture();
  16382. if (!internalTexture) {
  16383. return;
  16384. }
  16385. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16386. var value = texture.anisotropicFilteringLevel;
  16387. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16388. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16389. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16390. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16391. }
  16392. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16393. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16394. internalTexture._cachedAnisotropicFilteringLevel = value;
  16395. }
  16396. };
  16397. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16398. this._bindTextureDirectly(target, texture, true, true);
  16399. this._gl.texParameterf(target, parameter, value);
  16400. };
  16401. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16402. if (texture) {
  16403. this._bindTextureDirectly(target, texture, true, true);
  16404. }
  16405. this._gl.texParameteri(target, parameter, value);
  16406. };
  16407. /**
  16408. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16409. * @param x defines the x coordinate of the rectangle where pixels must be read
  16410. * @param y defines the y coordinate of the rectangle where pixels must be read
  16411. * @param width defines the width of the rectangle where pixels must be read
  16412. * @param height defines the height of the rectangle where pixels must be read
  16413. * @returns a Uint8Array containing RGBA colors
  16414. */
  16415. Engine.prototype.readPixels = function (x, y, width, height) {
  16416. var data = new Uint8Array(height * width * 4);
  16417. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16418. return data;
  16419. };
  16420. /**
  16421. * Add an externaly attached data from its key.
  16422. * This method call will fail and return false, if such key already exists.
  16423. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16424. * @param key the unique key that identifies the data
  16425. * @param data the data object to associate to the key for this Engine instance
  16426. * @return true if no such key were already present and the data was added successfully, false otherwise
  16427. */
  16428. Engine.prototype.addExternalData = function (key, data) {
  16429. if (!this._externalData) {
  16430. this._externalData = new BABYLON.StringDictionary();
  16431. }
  16432. return this._externalData.add(key, data);
  16433. };
  16434. /**
  16435. * Get an externaly attached data from its key
  16436. * @param key the unique key that identifies the data
  16437. * @return the associated data, if present (can be null), or undefined if not present
  16438. */
  16439. Engine.prototype.getExternalData = function (key) {
  16440. if (!this._externalData) {
  16441. this._externalData = new BABYLON.StringDictionary();
  16442. }
  16443. return this._externalData.get(key);
  16444. };
  16445. /**
  16446. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16447. * @param key the unique key that identifies the data
  16448. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16449. * @return the associated data, can be null if the factory returned null.
  16450. */
  16451. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16452. if (!this._externalData) {
  16453. this._externalData = new BABYLON.StringDictionary();
  16454. }
  16455. return this._externalData.getOrAddWithFactory(key, factory);
  16456. };
  16457. /**
  16458. * Remove an externaly attached data from the Engine instance
  16459. * @param key the unique key that identifies the data
  16460. * @return true if the data was successfully removed, false if it doesn't exist
  16461. */
  16462. Engine.prototype.removeExternalData = function (key) {
  16463. if (!this._externalData) {
  16464. this._externalData = new BABYLON.StringDictionary();
  16465. }
  16466. return this._externalData.remove(key);
  16467. };
  16468. /**
  16469. * Unbind all vertex attributes from the webGL context
  16470. */
  16471. Engine.prototype.unbindAllAttributes = function () {
  16472. if (this._mustWipeVertexAttributes) {
  16473. this._mustWipeVertexAttributes = false;
  16474. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16475. this._gl.disableVertexAttribArray(i);
  16476. this._vertexAttribArraysEnabled[i] = false;
  16477. this._currentBufferPointers[i].active = false;
  16478. }
  16479. return;
  16480. }
  16481. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16482. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16483. continue;
  16484. }
  16485. this._gl.disableVertexAttribArray(i);
  16486. this._vertexAttribArraysEnabled[i] = false;
  16487. this._currentBufferPointers[i].active = false;
  16488. }
  16489. };
  16490. /**
  16491. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16492. */
  16493. Engine.prototype.releaseEffects = function () {
  16494. for (var name in this._compiledEffects) {
  16495. this._deleteProgram(this._compiledEffects[name]._program);
  16496. }
  16497. this._compiledEffects = {};
  16498. };
  16499. /**
  16500. * Dispose and release all associated resources
  16501. */
  16502. Engine.prototype.dispose = function () {
  16503. this.hideLoadingUI();
  16504. this.stopRenderLoop();
  16505. // Release postProcesses
  16506. while (this.postProcesses.length) {
  16507. this.postProcesses[0].dispose();
  16508. }
  16509. // Empty texture
  16510. if (this._emptyTexture) {
  16511. this._releaseTexture(this._emptyTexture);
  16512. this._emptyTexture = null;
  16513. }
  16514. if (this._emptyCubeTexture) {
  16515. this._releaseTexture(this._emptyCubeTexture);
  16516. this._emptyCubeTexture = null;
  16517. }
  16518. // Rescale PP
  16519. if (this._rescalePostProcess) {
  16520. this._rescalePostProcess.dispose();
  16521. }
  16522. // Release scenes
  16523. while (this.scenes.length) {
  16524. this.scenes[0].dispose();
  16525. }
  16526. // Release audio engine
  16527. if (Engine.audioEngine) {
  16528. Engine.audioEngine.dispose();
  16529. }
  16530. // Release effects
  16531. this.releaseEffects();
  16532. // Unbind
  16533. this.unbindAllAttributes();
  16534. this._boundUniforms = [];
  16535. if (this._dummyFramebuffer) {
  16536. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16537. }
  16538. //WebVR
  16539. this.disableVR();
  16540. // Events
  16541. if (BABYLON.Tools.IsWindowObjectExist()) {
  16542. window.removeEventListener("blur", this._onBlur);
  16543. window.removeEventListener("focus", this._onFocus);
  16544. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16545. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16546. if (this._renderingCanvas) {
  16547. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16548. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16549. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16550. if (!this._doNotHandleContextLost) {
  16551. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16552. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16553. }
  16554. }
  16555. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16556. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16557. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16558. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16559. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16560. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16561. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16562. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16563. if (this._onVrDisplayConnect) {
  16564. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16565. if (this._onVrDisplayDisconnect) {
  16566. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16567. }
  16568. if (this._onVrDisplayPresentChange) {
  16569. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16570. }
  16571. this._onVrDisplayConnect = null;
  16572. this._onVrDisplayDisconnect = null;
  16573. }
  16574. }
  16575. // Remove from Instances
  16576. var index = Engine.Instances.indexOf(this);
  16577. if (index >= 0) {
  16578. Engine.Instances.splice(index, 1);
  16579. }
  16580. this._workingCanvas = null;
  16581. this._workingContext = null;
  16582. this._currentBufferPointers = [];
  16583. this._renderingCanvas = null;
  16584. this._currentProgram = null;
  16585. this._bindedRenderFunction = null;
  16586. this.onResizeObservable.clear();
  16587. this.onCanvasBlurObservable.clear();
  16588. this.onCanvasFocusObservable.clear();
  16589. this.onCanvasPointerOutObservable.clear();
  16590. this.onBeginFrameObservable.clear();
  16591. this.onEndFrameObservable.clear();
  16592. BABYLON.Effect.ResetCache();
  16593. // Abort active requests
  16594. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16595. var request = _a[_i];
  16596. request.abort();
  16597. }
  16598. };
  16599. // Loading screen
  16600. /**
  16601. * Display the loading screen
  16602. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16603. */
  16604. Engine.prototype.displayLoadingUI = function () {
  16605. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16606. return;
  16607. }
  16608. var loadingScreen = this.loadingScreen;
  16609. if (loadingScreen) {
  16610. loadingScreen.displayLoadingUI();
  16611. }
  16612. };
  16613. /**
  16614. * Hide the loading screen
  16615. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16616. */
  16617. Engine.prototype.hideLoadingUI = function () {
  16618. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16619. return;
  16620. }
  16621. var loadingScreen = this.loadingScreen;
  16622. if (loadingScreen) {
  16623. loadingScreen.hideLoadingUI();
  16624. }
  16625. };
  16626. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16627. /**
  16628. * Gets the current loading screen object
  16629. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16630. */
  16631. get: function () {
  16632. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16633. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16634. return this._loadingScreen;
  16635. },
  16636. /**
  16637. * Sets the current loading screen object
  16638. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16639. */
  16640. set: function (loadingScreen) {
  16641. this._loadingScreen = loadingScreen;
  16642. },
  16643. enumerable: true,
  16644. configurable: true
  16645. });
  16646. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16647. /**
  16648. * Sets the current loading screen text
  16649. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16650. */
  16651. set: function (text) {
  16652. this.loadingScreen.loadingUIText = text;
  16653. },
  16654. enumerable: true,
  16655. configurable: true
  16656. });
  16657. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16658. /**
  16659. * Sets the current loading screen background color
  16660. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16661. */
  16662. set: function (color) {
  16663. this.loadingScreen.loadingUIBackgroundColor = color;
  16664. },
  16665. enumerable: true,
  16666. configurable: true
  16667. });
  16668. /**
  16669. * Attach a new callback raised when context lost event is fired
  16670. * @param callback defines the callback to call
  16671. */
  16672. Engine.prototype.attachContextLostEvent = function (callback) {
  16673. if (this._renderingCanvas) {
  16674. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16675. }
  16676. };
  16677. /**
  16678. * Attach a new callback raised when context restored event is fired
  16679. * @param callback defines the callback to call
  16680. */
  16681. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16682. if (this._renderingCanvas) {
  16683. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16684. }
  16685. };
  16686. /**
  16687. * Gets the source code of the vertex shader associated with a specific webGL program
  16688. * @param program defines the program to use
  16689. * @returns a string containing the source code of the vertex shader associated with the program
  16690. */
  16691. Engine.prototype.getVertexShaderSource = function (program) {
  16692. var shaders = this._gl.getAttachedShaders(program);
  16693. if (!shaders) {
  16694. return null;
  16695. }
  16696. return this._gl.getShaderSource(shaders[0]);
  16697. };
  16698. /**
  16699. * Gets the source code of the fragment shader associated with a specific webGL program
  16700. * @param program defines the program to use
  16701. * @returns a string containing the source code of the fragment shader associated with the program
  16702. */
  16703. Engine.prototype.getFragmentShaderSource = function (program) {
  16704. var shaders = this._gl.getAttachedShaders(program);
  16705. if (!shaders) {
  16706. return null;
  16707. }
  16708. return this._gl.getShaderSource(shaders[1]);
  16709. };
  16710. /**
  16711. * Get the current error code of the webGL context
  16712. * @returns the error code
  16713. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16714. */
  16715. Engine.prototype.getError = function () {
  16716. return this._gl.getError();
  16717. };
  16718. // FPS
  16719. /**
  16720. * Gets the current framerate
  16721. * @returns a number representing the framerate
  16722. */
  16723. Engine.prototype.getFps = function () {
  16724. return this._fps;
  16725. };
  16726. /**
  16727. * Gets the time spent between current and previous frame
  16728. * @returns a number representing the delta time in ms
  16729. */
  16730. Engine.prototype.getDeltaTime = function () {
  16731. return this._deltaTime;
  16732. };
  16733. Engine.prototype._measureFps = function () {
  16734. this._performanceMonitor.sampleFrame();
  16735. this._fps = this._performanceMonitor.averageFPS;
  16736. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16737. };
  16738. /** @hidden */
  16739. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16740. if (faceIndex === void 0) { faceIndex = -1; }
  16741. if (level === void 0) { level = 0; }
  16742. var gl = this._gl;
  16743. if (!this._dummyFramebuffer) {
  16744. var dummy = gl.createFramebuffer();
  16745. if (!dummy) {
  16746. throw new Error("Unable to create dummy framebuffer");
  16747. }
  16748. this._dummyFramebuffer = dummy;
  16749. }
  16750. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16751. if (faceIndex > -1) {
  16752. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16753. }
  16754. else {
  16755. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16756. }
  16757. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16758. var buffer;
  16759. switch (readType) {
  16760. case gl.UNSIGNED_BYTE:
  16761. buffer = new Uint8Array(4 * width * height);
  16762. readType = gl.UNSIGNED_BYTE;
  16763. break;
  16764. default:
  16765. buffer = new Float32Array(4 * width * height);
  16766. readType = gl.FLOAT;
  16767. break;
  16768. }
  16769. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16770. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16771. return buffer;
  16772. };
  16773. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16774. if (this._webGLVersion > 1) {
  16775. return this._caps.colorBufferFloat;
  16776. }
  16777. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16778. };
  16779. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16780. if (this._webGLVersion > 1) {
  16781. return this._caps.colorBufferFloat;
  16782. }
  16783. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16784. };
  16785. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16786. Engine.prototype._canRenderToFramebuffer = function (type) {
  16787. var gl = this._gl;
  16788. //clear existing errors
  16789. while (gl.getError() !== gl.NO_ERROR) { }
  16790. var successful = true;
  16791. var texture = gl.createTexture();
  16792. gl.bindTexture(gl.TEXTURE_2D, texture);
  16793. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16794. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16795. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16796. var fb = gl.createFramebuffer();
  16797. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16798. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16799. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16800. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16801. successful = successful && (gl.getError() === gl.NO_ERROR);
  16802. //try render by clearing frame buffer's color buffer
  16803. if (successful) {
  16804. gl.clear(gl.COLOR_BUFFER_BIT);
  16805. successful = successful && (gl.getError() === gl.NO_ERROR);
  16806. }
  16807. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16808. if (successful) {
  16809. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16810. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16811. var readFormat = gl.RGBA;
  16812. var readType = gl.UNSIGNED_BYTE;
  16813. var buffer = new Uint8Array(4);
  16814. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16815. successful = successful && (gl.getError() === gl.NO_ERROR);
  16816. }
  16817. //clean up
  16818. gl.deleteTexture(texture);
  16819. gl.deleteFramebuffer(fb);
  16820. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16821. //clear accumulated errors
  16822. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16823. return successful;
  16824. };
  16825. /** @hidden */
  16826. Engine.prototype._getWebGLTextureType = function (type) {
  16827. if (type === Engine.TEXTURETYPE_FLOAT) {
  16828. return this._gl.FLOAT;
  16829. }
  16830. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16831. // Add Half Float Constant.
  16832. return this._gl.HALF_FLOAT_OES;
  16833. }
  16834. return this._gl.UNSIGNED_BYTE;
  16835. };
  16836. ;
  16837. Engine.prototype._getInternalFormat = function (format) {
  16838. var internalFormat = this._gl.RGBA;
  16839. switch (format) {
  16840. case Engine.TEXTUREFORMAT_ALPHA:
  16841. internalFormat = this._gl.ALPHA;
  16842. break;
  16843. case Engine.TEXTUREFORMAT_LUMINANCE:
  16844. internalFormat = this._gl.LUMINANCE;
  16845. break;
  16846. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16847. internalFormat = this._gl.LUMINANCE_ALPHA;
  16848. break;
  16849. case Engine.TEXTUREFORMAT_RGB:
  16850. internalFormat = this._gl.RGB;
  16851. break;
  16852. case Engine.TEXTUREFORMAT_RGBA:
  16853. internalFormat = this._gl.RGBA;
  16854. break;
  16855. case Engine.TEXTUREFORMAT_R:
  16856. internalFormat = this._gl.RED;
  16857. break;
  16858. case Engine.TEXTUREFORMAT_RG:
  16859. internalFormat = this._gl.RG;
  16860. break;
  16861. }
  16862. return internalFormat;
  16863. };
  16864. /** @hidden */
  16865. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16866. if (this._webGLVersion === 1) {
  16867. if (format !== undefined) {
  16868. switch (format) {
  16869. case Engine.TEXTUREFORMAT_LUMINANCE:
  16870. return this._gl.LUMINANCE;
  16871. case Engine.TEXTUREFORMAT_ALPHA:
  16872. return this._gl.ALPHA;
  16873. }
  16874. }
  16875. return this._gl.RGBA;
  16876. }
  16877. if (type === Engine.TEXTURETYPE_FLOAT) {
  16878. if (format !== undefined) {
  16879. switch (format) {
  16880. case Engine.TEXTUREFORMAT_R:
  16881. return this._gl.R32F;
  16882. case Engine.TEXTUREFORMAT_RG:
  16883. return this._gl.RG32F;
  16884. case Engine.TEXTUREFORMAT_RGB:
  16885. return this._gl.RGB32F;
  16886. }
  16887. }
  16888. return this._gl.RGBA32F;
  16889. }
  16890. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16891. if (format) {
  16892. switch (format) {
  16893. case Engine.TEXTUREFORMAT_R:
  16894. return this._gl.R16F;
  16895. case Engine.TEXTUREFORMAT_RG:
  16896. return this._gl.RG16F;
  16897. case Engine.TEXTUREFORMAT_RGB:
  16898. return this._gl.RGB16F;
  16899. }
  16900. }
  16901. return this._gl.RGBA16F;
  16902. }
  16903. if (format !== undefined) {
  16904. switch (format) {
  16905. case Engine.TEXTUREFORMAT_LUMINANCE:
  16906. return this._gl.LUMINANCE;
  16907. case Engine.TEXTUREFORMAT_RGB:
  16908. return this._gl.RGB;
  16909. case Engine.TEXTUREFORMAT_R:
  16910. return this._gl.R8;
  16911. case Engine.TEXTUREFORMAT_RG:
  16912. return this._gl.RG8;
  16913. case Engine.TEXTUREFORMAT_ALPHA:
  16914. return this._gl.ALPHA;
  16915. }
  16916. }
  16917. return this._gl.RGBA;
  16918. };
  16919. ;
  16920. /** @hidden */
  16921. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16922. if (type === Engine.TEXTURETYPE_FLOAT) {
  16923. return this._gl.RGBA32F;
  16924. }
  16925. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16926. return this._gl.RGBA16F;
  16927. }
  16928. return this._gl.RGBA8;
  16929. };
  16930. ;
  16931. /** @hidden */
  16932. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16933. var _this = this;
  16934. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16935. this._activeRequests.push(request);
  16936. request.onCompleteObservable.add(function (request) {
  16937. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16938. });
  16939. return request;
  16940. };
  16941. /** @hidden */
  16942. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16943. var _this = this;
  16944. return new Promise(function (resolve, reject) {
  16945. _this._loadFile(url, function (data) {
  16946. resolve(data);
  16947. }, undefined, database, useArrayBuffer, function (request, exception) {
  16948. reject(exception);
  16949. });
  16950. });
  16951. };
  16952. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16953. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16954. var onload = function (data) {
  16955. loadedFiles[index] = data;
  16956. loadedFiles._internalCount++;
  16957. if (loadedFiles._internalCount === 6) {
  16958. onfinish(loadedFiles);
  16959. }
  16960. };
  16961. var onerror = function (request, exception) {
  16962. if (onErrorCallBack && request) {
  16963. onErrorCallBack(request.status + " " + request.statusText, exception);
  16964. }
  16965. };
  16966. this._loadFile(url, onload, undefined, undefined, true, onerror);
  16967. };
  16968. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  16969. if (onError === void 0) { onError = null; }
  16970. var loadedFiles = [];
  16971. loadedFiles._internalCount = 0;
  16972. for (var index = 0; index < 6; index++) {
  16973. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  16974. }
  16975. };
  16976. // Statics
  16977. /**
  16978. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  16979. * @returns true if the engine can be created
  16980. * @ignorenaming
  16981. */
  16982. Engine.isSupported = function () {
  16983. try {
  16984. var tempcanvas = document.createElement("canvas");
  16985. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  16986. return gl != null && !!window.WebGLRenderingContext;
  16987. }
  16988. catch (e) {
  16989. return false;
  16990. }
  16991. };
  16992. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  16993. Engine.ExceptionList = [
  16994. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  16995. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16996. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16997. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16998. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16999. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17000. ];
  17001. /** Gets the list of created engines */
  17002. Engine.Instances = new Array();
  17003. /**
  17004. * Hidden
  17005. */
  17006. Engine._TextureLoaders = [];
  17007. // Const statics
  17008. /** Defines that alpha blending is disabled */
  17009. Engine.ALPHA_DISABLE = 0;
  17010. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17011. Engine.ALPHA_ADD = 1;
  17012. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17013. Engine.ALPHA_COMBINE = 2;
  17014. /** Defines that alpha blending to DEST - SRC * DEST */
  17015. Engine.ALPHA_SUBTRACT = 3;
  17016. /** Defines that alpha blending to SRC * DEST */
  17017. Engine.ALPHA_MULTIPLY = 4;
  17018. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17019. Engine.ALPHA_MAXIMIZED = 5;
  17020. /** Defines that alpha blending to SRC + DEST */
  17021. Engine.ALPHA_ONEONE = 6;
  17022. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17023. Engine.ALPHA_PREMULTIPLIED = 7;
  17024. /**
  17025. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17026. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17027. */
  17028. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17029. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17030. Engine.ALPHA_INTERPOLATE = 9;
  17031. /**
  17032. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17033. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17034. */
  17035. Engine.ALPHA_SCREENMODE = 10;
  17036. /** Defines that the ressource is not delayed*/
  17037. Engine.DELAYLOADSTATE_NONE = 0;
  17038. /** Defines that the ressource was successfully delay loaded */
  17039. Engine.DELAYLOADSTATE_LOADED = 1;
  17040. /** Defines that the ressource is currently delay loading */
  17041. Engine.DELAYLOADSTATE_LOADING = 2;
  17042. /** Defines that the ressource is delayed and has not started loading */
  17043. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17044. // Depht or Stencil test Constants.
  17045. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17046. Engine.NEVER = 0x0200;
  17047. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  17048. Engine.ALWAYS = 0x0207;
  17049. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17050. Engine.LESS = 0x0201;
  17051. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17052. Engine.EQUAL = 0x0202;
  17053. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  17054. Engine.LEQUAL = 0x0203;
  17055. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17056. Engine.GREATER = 0x0204;
  17057. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  17058. Engine.GEQUAL = 0x0206;
  17059. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  17060. Engine.NOTEQUAL = 0x0205;
  17061. // Stencil Actions Constants.
  17062. /** Passed to stencilOperation to specify that stencil value must be kept */
  17063. Engine.KEEP = 0x1E00;
  17064. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17065. Engine.REPLACE = 0x1E01;
  17066. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17067. Engine.INCR = 0x1E02;
  17068. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17069. Engine.DECR = 0x1E03;
  17070. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17071. Engine.INVERT = 0x150A;
  17072. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17073. Engine.INCR_WRAP = 0x8507;
  17074. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17075. Engine.DECR_WRAP = 0x8508;
  17076. /** Texture is not repeating outside of 0..1 UVs */
  17077. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17078. /** Texture is repeating outside of 0..1 UVs */
  17079. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17080. /** Texture is repeating and mirrored */
  17081. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17082. /** ALPHA */
  17083. Engine.TEXTUREFORMAT_ALPHA = 0;
  17084. /** LUMINANCE */
  17085. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17086. /** LUMINANCE_ALPHA */
  17087. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17088. /** RGB */
  17089. Engine.TEXTUREFORMAT_RGB = 4;
  17090. /** RGBA */
  17091. Engine.TEXTUREFORMAT_RGBA = 5;
  17092. /** R */
  17093. Engine.TEXTUREFORMAT_R = 6;
  17094. /** RG */
  17095. Engine.TEXTUREFORMAT_RG = 7;
  17096. /** UNSIGNED_INT */
  17097. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17098. /** FLOAT */
  17099. Engine.TEXTURETYPE_FLOAT = 1;
  17100. /** HALF_FLOAT */
  17101. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17102. /** nearest is mag = nearest and min = nearest and mip = linear */
  17103. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17104. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17105. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17106. /** Trilinear is mag = linear and min = linear and mip = linear */
  17107. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17108. /** nearest is mag = nearest and min = nearest and mip = linear */
  17109. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17110. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17111. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17112. /** Trilinear is mag = linear and min = linear and mip = linear */
  17113. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17114. /** mag = nearest and min = nearest and mip = nearest */
  17115. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17116. /** mag = nearest and min = linear and mip = nearest */
  17117. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17118. /** mag = nearest and min = linear and mip = linear */
  17119. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17120. /** mag = nearest and min = linear and mip = none */
  17121. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17122. /** mag = nearest and min = nearest and mip = none */
  17123. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17124. /** mag = linear and min = nearest and mip = nearest */
  17125. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17126. /** mag = linear and min = nearest and mip = linear */
  17127. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17128. /** mag = linear and min = linear and mip = none */
  17129. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17130. /** mag = linear and min = nearest and mip = none */
  17131. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17132. /** Explicit coordinates mode */
  17133. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17134. /** Spherical coordinates mode */
  17135. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17136. /** Planar coordinates mode */
  17137. Engine.TEXTURE_PLANAR_MODE = 2;
  17138. /** Cubic coordinates mode */
  17139. Engine.TEXTURE_CUBIC_MODE = 3;
  17140. /** Projection coordinates mode */
  17141. Engine.TEXTURE_PROJECTION_MODE = 4;
  17142. /** Skybox coordinates mode */
  17143. Engine.TEXTURE_SKYBOX_MODE = 5;
  17144. /** Inverse Cubic coordinates mode */
  17145. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17146. /** Equirectangular coordinates mode */
  17147. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17148. /** Equirectangular Fixed coordinates mode */
  17149. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17150. /** Equirectangular Fixed Mirrored coordinates mode */
  17151. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17152. // Texture rescaling mode
  17153. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17154. Engine.SCALEMODE_FLOOR = 1;
  17155. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17156. Engine.SCALEMODE_NEAREST = 2;
  17157. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17158. Engine.SCALEMODE_CEILING = 3;
  17159. // Updatable statics so stick with vars here
  17160. /**
  17161. * Gets or sets the epsilon value used by collision engine
  17162. */
  17163. Engine.CollisionsEpsilon = 0.001;
  17164. /**
  17165. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17166. */
  17167. Engine.CodeRepository = "src/";
  17168. /**
  17169. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17170. */
  17171. Engine.ShadersRepository = "src/Shaders/";
  17172. return Engine;
  17173. }());
  17174. BABYLON.Engine = Engine;
  17175. })(BABYLON || (BABYLON = {}));
  17176. //# sourceMappingURL=babylon.engine.js.map
  17177. var BABYLON;
  17178. (function (BABYLON) {
  17179. /**
  17180. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17181. */
  17182. var Node = /** @class */ (function () {
  17183. /**
  17184. * Creates a new Node
  17185. * @param {string} name - the name and id to be given to this node
  17186. * @param {BABYLON.Scene} the scene this node will be added to
  17187. */
  17188. function Node(name, scene) {
  17189. if (scene === void 0) { scene = null; }
  17190. /**
  17191. * Gets or sets a string used to store user defined state for the node
  17192. */
  17193. this.state = "";
  17194. /**
  17195. * Gets or sets an object used to store user defined information for the node
  17196. */
  17197. this.metadata = null;
  17198. /**
  17199. * Gets or sets a boolean used to define if the node must be serialized
  17200. */
  17201. this.doNotSerialize = false;
  17202. /** @hidden */
  17203. this._isDisposed = false;
  17204. /**
  17205. * Gets a list of Animations associated with the node
  17206. */
  17207. this.animations = new Array();
  17208. this._ranges = {};
  17209. this._isEnabled = true;
  17210. this._isReady = true;
  17211. /** @hidden */
  17212. this._currentRenderId = -1;
  17213. this._parentRenderId = -1;
  17214. this._childRenderId = -1;
  17215. this._animationPropertiesOverride = null;
  17216. /**
  17217. * An event triggered when the mesh is disposed
  17218. */
  17219. this.onDisposeObservable = new BABYLON.Observable();
  17220. // Behaviors
  17221. this._behaviors = new Array();
  17222. this.name = name;
  17223. this.id = name;
  17224. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17225. this.uniqueId = this._scene.getUniqueId();
  17226. this._initCache();
  17227. }
  17228. /**
  17229. * Add a new node constructor
  17230. * @param type defines the type name of the node to construct
  17231. * @param constructorFunc defines the constructor function
  17232. */
  17233. Node.AddNodeConstructor = function (type, constructorFunc) {
  17234. this._NodeConstructors[type] = constructorFunc;
  17235. };
  17236. /**
  17237. * Returns a node constructor based on type name
  17238. * @param type defines the type name
  17239. * @param name defines the new node name
  17240. * @param scene defines the hosting scene
  17241. * @param options defines optional options to transmit to constructors
  17242. * @returns the new constructor or null
  17243. */
  17244. Node.Construct = function (type, name, scene, options) {
  17245. var constructorFunc = this._NodeConstructors[type];
  17246. if (!constructorFunc) {
  17247. return null;
  17248. }
  17249. return constructorFunc(name, scene, options);
  17250. };
  17251. /**
  17252. * Gets a boolean indicating if the node has been disposed
  17253. * @returns true if the node was disposed
  17254. */
  17255. Node.prototype.isDisposed = function () {
  17256. return this._isDisposed;
  17257. };
  17258. Object.defineProperty(Node.prototype, "parent", {
  17259. get: function () {
  17260. return this._parentNode;
  17261. },
  17262. /**
  17263. * Gets or sets the parent of the node
  17264. */
  17265. set: function (parent) {
  17266. if (this._parentNode === parent) {
  17267. return;
  17268. }
  17269. // Remove self from list of children of parent
  17270. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17271. var index = this._parentNode._children.indexOf(this);
  17272. if (index !== -1) {
  17273. this._parentNode._children.splice(index, 1);
  17274. }
  17275. }
  17276. // Store new parent
  17277. this._parentNode = parent;
  17278. // Add as child to new parent
  17279. if (this._parentNode) {
  17280. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17281. this._parentNode._children = new Array();
  17282. }
  17283. this._parentNode._children.push(this);
  17284. }
  17285. },
  17286. enumerable: true,
  17287. configurable: true
  17288. });
  17289. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17290. /**
  17291. * Gets or sets the animation properties override
  17292. */
  17293. get: function () {
  17294. if (!this._animationPropertiesOverride) {
  17295. return this._scene.animationPropertiesOverride;
  17296. }
  17297. return this._animationPropertiesOverride;
  17298. },
  17299. set: function (value) {
  17300. this._animationPropertiesOverride = value;
  17301. },
  17302. enumerable: true,
  17303. configurable: true
  17304. });
  17305. /**
  17306. * Gets a string idenfifying the name of the class
  17307. * @returns "Node" string
  17308. */
  17309. Node.prototype.getClassName = function () {
  17310. return "Node";
  17311. };
  17312. Object.defineProperty(Node.prototype, "onDispose", {
  17313. /**
  17314. * Sets a callback that will be raised when the node will be disposed
  17315. */
  17316. set: function (callback) {
  17317. if (this._onDisposeObserver) {
  17318. this.onDisposeObservable.remove(this._onDisposeObserver);
  17319. }
  17320. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17321. },
  17322. enumerable: true,
  17323. configurable: true
  17324. });
  17325. /**
  17326. * Gets the scene of the node
  17327. * @returns a {BABYLON.Scene}
  17328. */
  17329. Node.prototype.getScene = function () {
  17330. return this._scene;
  17331. };
  17332. /**
  17333. * Gets the engine of the node
  17334. * @returns a {BABYLON.Engine}
  17335. */
  17336. Node.prototype.getEngine = function () {
  17337. return this._scene.getEngine();
  17338. };
  17339. /**
  17340. * Attach a behavior to the node
  17341. * @see http://doc.babylonjs.com/features/behaviour
  17342. * @param behavior defines the behavior to attach
  17343. * @returns the current Node
  17344. */
  17345. Node.prototype.addBehavior = function (behavior) {
  17346. var _this = this;
  17347. var index = this._behaviors.indexOf(behavior);
  17348. if (index !== -1) {
  17349. return this;
  17350. }
  17351. behavior.init();
  17352. if (this._scene.isLoading) {
  17353. // We defer the attach when the scene will be loaded
  17354. this._scene.onDataLoadedObservable.addOnce(function () {
  17355. behavior.attach(_this);
  17356. });
  17357. }
  17358. else {
  17359. behavior.attach(this);
  17360. }
  17361. this._behaviors.push(behavior);
  17362. return this;
  17363. };
  17364. /**
  17365. * Remove an attached behavior
  17366. * @see http://doc.babylonjs.com/features/behaviour
  17367. * @param behavior defines the behavior to attach
  17368. * @returns the current Node
  17369. */
  17370. Node.prototype.removeBehavior = function (behavior) {
  17371. var index = this._behaviors.indexOf(behavior);
  17372. if (index === -1) {
  17373. return this;
  17374. }
  17375. this._behaviors[index].detach();
  17376. this._behaviors.splice(index, 1);
  17377. return this;
  17378. };
  17379. Object.defineProperty(Node.prototype, "behaviors", {
  17380. /**
  17381. * Gets the list of attached behaviors
  17382. * @see http://doc.babylonjs.com/features/behaviour
  17383. */
  17384. get: function () {
  17385. return this._behaviors;
  17386. },
  17387. enumerable: true,
  17388. configurable: true
  17389. });
  17390. /**
  17391. * Gets an attached behavior by name
  17392. * @param name defines the name of the behavior to look for
  17393. * @see http://doc.babylonjs.com/features/behaviour
  17394. * @returns null if behavior was not found else the requested behavior
  17395. */
  17396. Node.prototype.getBehaviorByName = function (name) {
  17397. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17398. var behavior = _a[_i];
  17399. if (behavior.name === name) {
  17400. return behavior;
  17401. }
  17402. }
  17403. return null;
  17404. };
  17405. /**
  17406. * Returns the world matrix of the node
  17407. * @returns a matrix containing the node's world matrix
  17408. */
  17409. Node.prototype.getWorldMatrix = function () {
  17410. return BABYLON.Matrix.Identity();
  17411. };
  17412. /** @hidden */
  17413. Node.prototype._getWorldMatrixDeterminant = function () {
  17414. return 1;
  17415. };
  17416. // override it in derived class if you add new variables to the cache
  17417. // and call the parent class method
  17418. /** @hidden */
  17419. Node.prototype._initCache = function () {
  17420. this._cache = {};
  17421. this._cache.parent = undefined;
  17422. };
  17423. /** @hidden */
  17424. Node.prototype.updateCache = function (force) {
  17425. if (!force && this.isSynchronized())
  17426. return;
  17427. this._cache.parent = this.parent;
  17428. this._updateCache();
  17429. };
  17430. // override it in derived class if you add new variables to the cache
  17431. // and call the parent class method if !ignoreParentClass
  17432. /** @hidden */
  17433. Node.prototype._updateCache = function (ignoreParentClass) {
  17434. };
  17435. // override it in derived class if you add new variables to the cache
  17436. /** @hidden */
  17437. Node.prototype._isSynchronized = function () {
  17438. return true;
  17439. };
  17440. /** @hidden */
  17441. Node.prototype._markSyncedWithParent = function () {
  17442. if (this.parent) {
  17443. this._parentRenderId = this.parent._childRenderId;
  17444. }
  17445. };
  17446. /** @hidden */
  17447. Node.prototype.isSynchronizedWithParent = function () {
  17448. if (!this.parent) {
  17449. return true;
  17450. }
  17451. if (this._parentRenderId !== this.parent._childRenderId) {
  17452. return false;
  17453. }
  17454. return this.parent.isSynchronized();
  17455. };
  17456. /** @hidden */
  17457. Node.prototype.isSynchronized = function (updateCache) {
  17458. var check = this.hasNewParent();
  17459. check = check || !this.isSynchronizedWithParent();
  17460. check = check || !this._isSynchronized();
  17461. if (updateCache)
  17462. this.updateCache(true);
  17463. return !check;
  17464. };
  17465. /** @hidden */
  17466. Node.prototype.hasNewParent = function (update) {
  17467. if (this._cache.parent === this.parent)
  17468. return false;
  17469. if (update)
  17470. this._cache.parent = this.parent;
  17471. return true;
  17472. };
  17473. /**
  17474. * Is this node ready to be used/rendered
  17475. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17476. * @return true if the node is ready
  17477. */
  17478. Node.prototype.isReady = function (completeCheck) {
  17479. if (completeCheck === void 0) { completeCheck = false; }
  17480. return this._isReady;
  17481. };
  17482. /**
  17483. * Is this node enabled?
  17484. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  17485. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  17486. * @return whether this node (and its parent) is enabled
  17487. */
  17488. Node.prototype.isEnabled = function (checkAncestors) {
  17489. if (checkAncestors === void 0) { checkAncestors = true; }
  17490. if (checkAncestors === false) {
  17491. return this._isEnabled;
  17492. }
  17493. if (this._isEnabled === false) {
  17494. return false;
  17495. }
  17496. if (this.parent !== undefined && this.parent !== null) {
  17497. return this.parent.isEnabled(checkAncestors);
  17498. }
  17499. return true;
  17500. };
  17501. /**
  17502. * Set the enabled state of this node
  17503. * @param value defines the new enabled state
  17504. */
  17505. Node.prototype.setEnabled = function (value) {
  17506. this._isEnabled = value;
  17507. };
  17508. /**
  17509. * Is this node a descendant of the given node?
  17510. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17511. * @param ancestor defines the parent node to inspect
  17512. * @returns a boolean indicating if this node is a descendant of the given node
  17513. */
  17514. Node.prototype.isDescendantOf = function (ancestor) {
  17515. if (this.parent) {
  17516. if (this.parent === ancestor) {
  17517. return true;
  17518. }
  17519. return this.parent.isDescendantOf(ancestor);
  17520. }
  17521. return false;
  17522. };
  17523. /** @hidden */
  17524. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17525. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17526. if (!this._children) {
  17527. return;
  17528. }
  17529. for (var index = 0; index < this._children.length; index++) {
  17530. var item = this._children[index];
  17531. if (!predicate || predicate(item)) {
  17532. results.push(item);
  17533. }
  17534. if (!directDescendantsOnly) {
  17535. item._getDescendants(results, false, predicate);
  17536. }
  17537. }
  17538. };
  17539. /**
  17540. * Will return all nodes that have this node as ascendant
  17541. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17542. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17543. * @return all children nodes of all types
  17544. */
  17545. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17546. var results = new Array();
  17547. this._getDescendants(results, directDescendantsOnly, predicate);
  17548. return results;
  17549. };
  17550. /**
  17551. * Get all child-meshes of this node
  17552. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17553. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17554. * @returns an array of {BABYLON.AbstractMesh}
  17555. */
  17556. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17557. var results = [];
  17558. this._getDescendants(results, directDescendantsOnly, function (node) {
  17559. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17560. });
  17561. return results;
  17562. };
  17563. /**
  17564. * Get all child-transformNodes of this node
  17565. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17566. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17567. * @returns an array of {BABYLON.TransformNode}
  17568. */
  17569. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17570. var results = [];
  17571. this._getDescendants(results, directDescendantsOnly, function (node) {
  17572. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17573. });
  17574. return results;
  17575. };
  17576. /**
  17577. * Get all direct children of this node
  17578. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17579. * @returns an array of {BABYLON.Node}
  17580. */
  17581. Node.prototype.getChildren = function (predicate) {
  17582. return this.getDescendants(true, predicate);
  17583. };
  17584. /** @hidden */
  17585. Node.prototype._setReady = function (state) {
  17586. if (state === this._isReady) {
  17587. return;
  17588. }
  17589. if (!state) {
  17590. this._isReady = false;
  17591. return;
  17592. }
  17593. if (this.onReady) {
  17594. this.onReady(this);
  17595. }
  17596. this._isReady = true;
  17597. };
  17598. /**
  17599. * Get an animation by name
  17600. * @param name defines the name of the animation to look for
  17601. * @returns null if not found else the requested animation
  17602. */
  17603. Node.prototype.getAnimationByName = function (name) {
  17604. for (var i = 0; i < this.animations.length; i++) {
  17605. var animation = this.animations[i];
  17606. if (animation.name === name) {
  17607. return animation;
  17608. }
  17609. }
  17610. return null;
  17611. };
  17612. /**
  17613. * Creates an animation range for this node
  17614. * @param name defines the name of the range
  17615. * @param from defines the starting key
  17616. * @param to defines the end key
  17617. */
  17618. Node.prototype.createAnimationRange = function (name, from, to) {
  17619. // check name not already in use
  17620. if (!this._ranges[name]) {
  17621. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17622. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17623. if (this.animations[i]) {
  17624. this.animations[i].createRange(name, from, to);
  17625. }
  17626. }
  17627. }
  17628. };
  17629. /**
  17630. * Delete a specific animation range
  17631. * @param name defines the name of the range to delete
  17632. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17633. */
  17634. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17635. if (deleteFrames === void 0) { deleteFrames = true; }
  17636. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17637. if (this.animations[i]) {
  17638. this.animations[i].deleteRange(name, deleteFrames);
  17639. }
  17640. }
  17641. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17642. };
  17643. /**
  17644. * Get an animation range by name
  17645. * @param name defines the name of the animation range to look for
  17646. * @returns null if not found else the requested animation range
  17647. */
  17648. Node.prototype.getAnimationRange = function (name) {
  17649. return this._ranges[name];
  17650. };
  17651. /**
  17652. * Will start the animation sequence
  17653. * @param name defines the range frames for animation sequence
  17654. * @param loop defines if the animation should loop (false by default)
  17655. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17656. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17657. * @returns the object created for this animation. If range does not exist, it will return null
  17658. */
  17659. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17660. var range = this.getAnimationRange(name);
  17661. if (!range) {
  17662. return null;
  17663. }
  17664. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17665. };
  17666. /**
  17667. * Serialize animation ranges into a JSON compatible object
  17668. * @returns serialization object
  17669. */
  17670. Node.prototype.serializeAnimationRanges = function () {
  17671. var serializationRanges = [];
  17672. for (var name in this._ranges) {
  17673. var localRange = this._ranges[name];
  17674. if (!localRange) {
  17675. continue;
  17676. }
  17677. var range = {};
  17678. range.name = name;
  17679. range.from = localRange.from;
  17680. range.to = localRange.to;
  17681. serializationRanges.push(range);
  17682. }
  17683. return serializationRanges;
  17684. };
  17685. /**
  17686. * Computes the world matrix of the node
  17687. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17688. * @returns the world matrix
  17689. */
  17690. Node.prototype.computeWorldMatrix = function (force) {
  17691. return BABYLON.Matrix.Identity();
  17692. };
  17693. /**
  17694. * Releases resources associated with this node.
  17695. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17696. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17697. */
  17698. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17699. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17700. if (!doNotRecurse) {
  17701. var nodes = this.getDescendants(true);
  17702. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17703. var node = nodes_1[_i];
  17704. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17705. }
  17706. }
  17707. else {
  17708. var transformNodes = this.getChildTransformNodes(true);
  17709. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17710. var transformNode = transformNodes_1[_a];
  17711. transformNode.parent = null;
  17712. transformNode.computeWorldMatrix(true);
  17713. }
  17714. }
  17715. this.parent = null;
  17716. // Callback
  17717. this.onDisposeObservable.notifyObservers(this);
  17718. this.onDisposeObservable.clear();
  17719. // Behaviors
  17720. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17721. var behavior = _c[_b];
  17722. behavior.detach();
  17723. }
  17724. this._behaviors = [];
  17725. this._isDisposed = true;
  17726. };
  17727. /**
  17728. * Parse animation range data from a serialization object and store them into a given node
  17729. * @param node defines where to store the animation ranges
  17730. * @param parsedNode defines the serialization object to read data from
  17731. * @param scene defines the hosting scene
  17732. */
  17733. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17734. if (parsedNode.ranges) {
  17735. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17736. var data = parsedNode.ranges[index];
  17737. node.createAnimationRange(data.name, data.from, data.to);
  17738. }
  17739. }
  17740. };
  17741. Node._NodeConstructors = {};
  17742. __decorate([
  17743. BABYLON.serialize()
  17744. ], Node.prototype, "name", void 0);
  17745. __decorate([
  17746. BABYLON.serialize()
  17747. ], Node.prototype, "id", void 0);
  17748. __decorate([
  17749. BABYLON.serialize()
  17750. ], Node.prototype, "uniqueId", void 0);
  17751. __decorate([
  17752. BABYLON.serialize()
  17753. ], Node.prototype, "state", void 0);
  17754. __decorate([
  17755. BABYLON.serialize()
  17756. ], Node.prototype, "metadata", void 0);
  17757. return Node;
  17758. }());
  17759. BABYLON.Node = Node;
  17760. })(BABYLON || (BABYLON = {}));
  17761. //# sourceMappingURL=babylon.node.js.map
  17762. var BABYLON;
  17763. (function (BABYLON) {
  17764. var BoundingSphere = /** @class */ (function () {
  17765. /**
  17766. * Creates a new bounding sphere
  17767. * @param min defines the minimum vector (in local space)
  17768. * @param max defines the maximum vector (in local space)
  17769. */
  17770. function BoundingSphere(min, max) {
  17771. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17772. this.reConstruct(min, max);
  17773. }
  17774. /**
  17775. * Recreates the entire bounding sphere from scratch
  17776. * @param min defines the new minimum vector (in local space)
  17777. * @param max defines the new maximum vector (in local space)
  17778. */
  17779. BoundingSphere.prototype.reConstruct = function (min, max) {
  17780. this.minimum = min.clone();
  17781. this.maximum = max.clone();
  17782. var distance = BABYLON.Vector3.Distance(min, max);
  17783. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17784. this.radius = distance * 0.5;
  17785. this.centerWorld = BABYLON.Vector3.Zero();
  17786. this._update(BABYLON.Matrix.Identity());
  17787. };
  17788. /**
  17789. * Scale the current bounding sphere by applying a scale factor
  17790. * @param factor defines the scale factor to apply
  17791. * @returns the current bounding box
  17792. */
  17793. BoundingSphere.prototype.scale = function (factor) {
  17794. var newRadius = this.radius * factor;
  17795. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17796. var min = this.center.subtract(newRadiusVector);
  17797. var max = this.center.add(newRadiusVector);
  17798. this.reConstruct(min, max);
  17799. return this;
  17800. };
  17801. // Methods
  17802. BoundingSphere.prototype._update = function (world) {
  17803. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17804. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17805. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17806. };
  17807. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17808. for (var i = 0; i < 6; i++) {
  17809. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17810. return false;
  17811. }
  17812. return true;
  17813. };
  17814. BoundingSphere.prototype.intersectsPoint = function (point) {
  17815. var x = this.centerWorld.x - point.x;
  17816. var y = this.centerWorld.y - point.y;
  17817. var z = this.centerWorld.z - point.z;
  17818. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17819. if (this.radiusWorld < distance)
  17820. return false;
  17821. return true;
  17822. };
  17823. // Statics
  17824. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17825. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17826. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17827. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17828. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17829. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17830. return false;
  17831. return true;
  17832. };
  17833. return BoundingSphere;
  17834. }());
  17835. BABYLON.BoundingSphere = BoundingSphere;
  17836. })(BABYLON || (BABYLON = {}));
  17837. //# sourceMappingURL=babylon.boundingSphere.js.map
  17838. var BABYLON;
  17839. (function (BABYLON) {
  17840. var BoundingBox = /** @class */ (function () {
  17841. /**
  17842. * Creates a new bounding box
  17843. * @param min defines the minimum vector (in local space)
  17844. * @param max defines the maximum vector (in local space)
  17845. */
  17846. function BoundingBox(min, max) {
  17847. this.vectorsWorld = new Array();
  17848. this.reConstruct(min, max);
  17849. }
  17850. // Methods
  17851. /**
  17852. * Recreates the entire bounding box from scratch
  17853. * @param min defines the new minimum vector (in local space)
  17854. * @param max defines the new maximum vector (in local space)
  17855. */
  17856. BoundingBox.prototype.reConstruct = function (min, max) {
  17857. this.minimum = min.clone();
  17858. this.maximum = max.clone();
  17859. // Bounding vectors
  17860. this.vectors = new Array();
  17861. this.vectors.push(this.minimum.clone());
  17862. this.vectors.push(this.maximum.clone());
  17863. this.vectors.push(this.minimum.clone());
  17864. this.vectors[2].x = this.maximum.x;
  17865. this.vectors.push(this.minimum.clone());
  17866. this.vectors[3].y = this.maximum.y;
  17867. this.vectors.push(this.minimum.clone());
  17868. this.vectors[4].z = this.maximum.z;
  17869. this.vectors.push(this.maximum.clone());
  17870. this.vectors[5].z = this.minimum.z;
  17871. this.vectors.push(this.maximum.clone());
  17872. this.vectors[6].x = this.minimum.x;
  17873. this.vectors.push(this.maximum.clone());
  17874. this.vectors[7].y = this.minimum.y;
  17875. // OBB
  17876. this.center = this.maximum.add(this.minimum).scale(0.5);
  17877. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17878. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17879. // World
  17880. for (var index = 0; index < this.vectors.length; index++) {
  17881. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17882. }
  17883. this.minimumWorld = BABYLON.Vector3.Zero();
  17884. this.maximumWorld = BABYLON.Vector3.Zero();
  17885. this.centerWorld = BABYLON.Vector3.Zero();
  17886. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17887. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17888. };
  17889. /**
  17890. * Scale the current bounding box by applying a scale factor
  17891. * @param factor defines the scale factor to apply
  17892. * @returns the current bounding box
  17893. */
  17894. BoundingBox.prototype.scale = function (factor) {
  17895. var diff = this.maximum.subtract(this.minimum);
  17896. var distance = diff.length() * factor;
  17897. diff.normalize();
  17898. var newRadius = diff.scale(distance / 2);
  17899. var min = this.center.subtract(newRadius);
  17900. var max = this.center.add(newRadius);
  17901. this.reConstruct(min, max);
  17902. return this;
  17903. };
  17904. BoundingBox.prototype.getWorldMatrix = function () {
  17905. return this._worldMatrix;
  17906. };
  17907. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17908. this._worldMatrix.copyFrom(matrix);
  17909. return this;
  17910. };
  17911. BoundingBox.prototype._update = function (world) {
  17912. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17913. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17914. for (var index = 0; index < this.vectors.length; index++) {
  17915. var v = this.vectorsWorld[index];
  17916. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17917. if (v.x < this.minimumWorld.x)
  17918. this.minimumWorld.x = v.x;
  17919. if (v.y < this.minimumWorld.y)
  17920. this.minimumWorld.y = v.y;
  17921. if (v.z < this.minimumWorld.z)
  17922. this.minimumWorld.z = v.z;
  17923. if (v.x > this.maximumWorld.x)
  17924. this.maximumWorld.x = v.x;
  17925. if (v.y > this.maximumWorld.y)
  17926. this.maximumWorld.y = v.y;
  17927. if (v.z > this.maximumWorld.z)
  17928. this.maximumWorld.z = v.z;
  17929. }
  17930. // Extend
  17931. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17932. this.extendSizeWorld.scaleInPlace(0.5);
  17933. // OBB
  17934. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17935. this.centerWorld.scaleInPlace(0.5);
  17936. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17937. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17938. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17939. this._worldMatrix = world;
  17940. };
  17941. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17942. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17943. };
  17944. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17945. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17946. };
  17947. BoundingBox.prototype.intersectsPoint = function (point) {
  17948. var delta = -BABYLON.Epsilon;
  17949. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17950. return false;
  17951. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17952. return false;
  17953. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17954. return false;
  17955. return true;
  17956. };
  17957. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17958. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17959. };
  17960. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17961. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17962. return false;
  17963. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17964. return false;
  17965. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17966. return false;
  17967. return true;
  17968. };
  17969. // Statics
  17970. BoundingBox.Intersects = function (box0, box1) {
  17971. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17972. return false;
  17973. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17974. return false;
  17975. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17976. return false;
  17977. return true;
  17978. };
  17979. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17980. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17981. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17982. return (num <= (sphereRadius * sphereRadius));
  17983. };
  17984. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17985. for (var p = 0; p < 6; p++) {
  17986. for (var i = 0; i < 8; i++) {
  17987. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17988. return false;
  17989. }
  17990. }
  17991. }
  17992. return true;
  17993. };
  17994. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17995. for (var p = 0; p < 6; p++) {
  17996. var inCount = 8;
  17997. for (var i = 0; i < 8; i++) {
  17998. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17999. --inCount;
  18000. }
  18001. else {
  18002. break;
  18003. }
  18004. }
  18005. if (inCount === 0)
  18006. return false;
  18007. }
  18008. return true;
  18009. };
  18010. return BoundingBox;
  18011. }());
  18012. BABYLON.BoundingBox = BoundingBox;
  18013. })(BABYLON || (BABYLON = {}));
  18014. //# sourceMappingURL=babylon.boundingBox.js.map
  18015. var BABYLON;
  18016. (function (BABYLON) {
  18017. var computeBoxExtents = function (axis, box) {
  18018. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18019. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18020. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18021. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18022. var r = r0 + r1 + r2;
  18023. return {
  18024. min: p - r,
  18025. max: p + r
  18026. };
  18027. };
  18028. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18029. var axisOverlap = function (axis, box0, box1) {
  18030. var result0 = computeBoxExtents(axis, box0);
  18031. var result1 = computeBoxExtents(axis, box1);
  18032. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18033. };
  18034. var BoundingInfo = /** @class */ (function () {
  18035. function BoundingInfo(minimum, maximum) {
  18036. this.minimum = minimum;
  18037. this.maximum = maximum;
  18038. this._isLocked = false;
  18039. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18040. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18041. }
  18042. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18043. get: function () {
  18044. return this._isLocked;
  18045. },
  18046. set: function (value) {
  18047. this._isLocked = value;
  18048. },
  18049. enumerable: true,
  18050. configurable: true
  18051. });
  18052. // Methods
  18053. BoundingInfo.prototype.update = function (world) {
  18054. if (this._isLocked) {
  18055. return;
  18056. }
  18057. this.boundingBox._update(world);
  18058. this.boundingSphere._update(world);
  18059. };
  18060. /**
  18061. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18062. * @param center New center of the bounding info
  18063. * @param extend New extend of the bounding info
  18064. */
  18065. BoundingInfo.prototype.centerOn = function (center, extend) {
  18066. this.minimum = center.subtract(extend);
  18067. this.maximum = center.add(extend);
  18068. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18069. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18070. return this;
  18071. };
  18072. /**
  18073. * Scale the current bounding info by applying a scale factor
  18074. * @param factor defines the scale factor to apply
  18075. * @returns the current bounding info
  18076. */
  18077. BoundingInfo.prototype.scale = function (factor) {
  18078. this.boundingBox.scale(factor);
  18079. this.boundingSphere.scale(factor);
  18080. return this;
  18081. };
  18082. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18083. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18084. return false;
  18085. return this.boundingBox.isInFrustum(frustumPlanes);
  18086. };
  18087. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18088. /**
  18089. * Gets the world distance between the min and max points of the bounding box
  18090. */
  18091. get: function () {
  18092. var boundingBox = this.boundingBox;
  18093. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18094. return size.length();
  18095. },
  18096. enumerable: true,
  18097. configurable: true
  18098. });
  18099. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18100. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18101. };
  18102. BoundingInfo.prototype._checkCollision = function (collider) {
  18103. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18104. };
  18105. BoundingInfo.prototype.intersectsPoint = function (point) {
  18106. if (!this.boundingSphere.centerWorld) {
  18107. return false;
  18108. }
  18109. if (!this.boundingSphere.intersectsPoint(point)) {
  18110. return false;
  18111. }
  18112. if (!this.boundingBox.intersectsPoint(point)) {
  18113. return false;
  18114. }
  18115. return true;
  18116. };
  18117. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18118. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18119. return false;
  18120. }
  18121. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18122. return false;
  18123. }
  18124. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18125. return false;
  18126. }
  18127. if (!precise) {
  18128. return true;
  18129. }
  18130. var box0 = this.boundingBox;
  18131. var box1 = boundingInfo.boundingBox;
  18132. if (!axisOverlap(box0.directions[0], box0, box1))
  18133. return false;
  18134. if (!axisOverlap(box0.directions[1], box0, box1))
  18135. return false;
  18136. if (!axisOverlap(box0.directions[2], box0, box1))
  18137. return false;
  18138. if (!axisOverlap(box1.directions[0], box0, box1))
  18139. return false;
  18140. if (!axisOverlap(box1.directions[1], box0, box1))
  18141. return false;
  18142. if (!axisOverlap(box1.directions[2], box0, box1))
  18143. return false;
  18144. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18145. return false;
  18146. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18147. return false;
  18148. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18149. return false;
  18150. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18151. return false;
  18152. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18153. return false;
  18154. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18155. return false;
  18156. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18157. return false;
  18158. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18159. return false;
  18160. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18161. return false;
  18162. return true;
  18163. };
  18164. return BoundingInfo;
  18165. }());
  18166. BABYLON.BoundingInfo = BoundingInfo;
  18167. })(BABYLON || (BABYLON = {}));
  18168. //# sourceMappingURL=babylon.boundingInfo.js.map
  18169. var BABYLON;
  18170. (function (BABYLON) {
  18171. var TransformNode = /** @class */ (function (_super) {
  18172. __extends(TransformNode, _super);
  18173. function TransformNode(name, scene, isPure) {
  18174. if (scene === void 0) { scene = null; }
  18175. if (isPure === void 0) { isPure = true; }
  18176. var _this = _super.call(this, name, scene) || this;
  18177. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18178. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18179. _this._up = new BABYLON.Vector3(0, 1, 0);
  18180. _this._right = new BABYLON.Vector3(1, 0, 0);
  18181. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18182. // Properties
  18183. _this._rotation = BABYLON.Vector3.Zero();
  18184. _this._scaling = BABYLON.Vector3.One();
  18185. _this._isDirty = false;
  18186. /**
  18187. * Set the billboard mode. Default is 0.
  18188. *
  18189. * | Value | Type | Description |
  18190. * | --- | --- | --- |
  18191. * | 0 | BILLBOARDMODE_NONE | |
  18192. * | 1 | BILLBOARDMODE_X | |
  18193. * | 2 | BILLBOARDMODE_Y | |
  18194. * | 4 | BILLBOARDMODE_Z | |
  18195. * | 7 | BILLBOARDMODE_ALL | |
  18196. *
  18197. */
  18198. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18199. _this.scalingDeterminant = 1;
  18200. _this.infiniteDistance = false;
  18201. /**
  18202. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18203. * By default the system will update normals to compensate
  18204. */
  18205. _this.ignoreNonUniformScaling = false;
  18206. _this.position = BABYLON.Vector3.Zero();
  18207. _this._localWorld = BABYLON.Matrix.Zero();
  18208. _this._worldMatrix = BABYLON.Matrix.Zero();
  18209. _this._worldMatrixDeterminant = 0;
  18210. _this._absolutePosition = BABYLON.Vector3.Zero();
  18211. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18212. _this._postMultiplyPivotMatrix = false;
  18213. _this._isWorldMatrixFrozen = false;
  18214. /**
  18215. * An event triggered after the world matrix is updated
  18216. */
  18217. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18218. _this._nonUniformScaling = false;
  18219. if (isPure) {
  18220. _this.getScene().addTransformNode(_this);
  18221. }
  18222. return _this;
  18223. }
  18224. /**
  18225. * Gets a string idenfifying the name of the class
  18226. * @returns "TransformNode" string
  18227. */
  18228. TransformNode.prototype.getClassName = function () {
  18229. return "TransformNode";
  18230. };
  18231. Object.defineProperty(TransformNode.prototype, "rotation", {
  18232. /**
  18233. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18234. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18235. * Default : (0.0, 0.0, 0.0)
  18236. */
  18237. get: function () {
  18238. return this._rotation;
  18239. },
  18240. set: function (newRotation) {
  18241. this._rotation = newRotation;
  18242. },
  18243. enumerable: true,
  18244. configurable: true
  18245. });
  18246. Object.defineProperty(TransformNode.prototype, "scaling", {
  18247. /**
  18248. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18249. * Default : (1.0, 1.0, 1.0)
  18250. */
  18251. get: function () {
  18252. return this._scaling;
  18253. },
  18254. /**
  18255. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18256. * Default : (1.0, 1.0, 1.0)
  18257. */
  18258. set: function (newScaling) {
  18259. this._scaling = newScaling;
  18260. },
  18261. enumerable: true,
  18262. configurable: true
  18263. });
  18264. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18265. /**
  18266. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18267. * It's null by default.
  18268. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18269. */
  18270. get: function () {
  18271. return this._rotationQuaternion;
  18272. },
  18273. set: function (quaternion) {
  18274. this._rotationQuaternion = quaternion;
  18275. //reset the rotation vector.
  18276. if (quaternion && this.rotation.length()) {
  18277. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18278. }
  18279. },
  18280. enumerable: true,
  18281. configurable: true
  18282. });
  18283. Object.defineProperty(TransformNode.prototype, "forward", {
  18284. /**
  18285. * The forward direction of that transform in world space.
  18286. */
  18287. get: function () {
  18288. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18289. },
  18290. enumerable: true,
  18291. configurable: true
  18292. });
  18293. Object.defineProperty(TransformNode.prototype, "up", {
  18294. /**
  18295. * The up direction of that transform in world space.
  18296. */
  18297. get: function () {
  18298. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18299. },
  18300. enumerable: true,
  18301. configurable: true
  18302. });
  18303. Object.defineProperty(TransformNode.prototype, "right", {
  18304. /**
  18305. * The right direction of that transform in world space.
  18306. */
  18307. get: function () {
  18308. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18309. },
  18310. enumerable: true,
  18311. configurable: true
  18312. });
  18313. /**
  18314. * Returns the latest update of the World matrix
  18315. * Returns a Matrix.
  18316. */
  18317. TransformNode.prototype.getWorldMatrix = function () {
  18318. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18319. this.computeWorldMatrix();
  18320. }
  18321. return this._worldMatrix;
  18322. };
  18323. /** @hidden */
  18324. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18325. return this._worldMatrixDeterminant;
  18326. };
  18327. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18328. /**
  18329. * Returns directly the latest state of the mesh World matrix.
  18330. * A Matrix is returned.
  18331. */
  18332. get: function () {
  18333. return this._worldMatrix;
  18334. },
  18335. enumerable: true,
  18336. configurable: true
  18337. });
  18338. /**
  18339. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18340. * Returns the TransformNode.
  18341. */
  18342. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18343. this._poseMatrix.copyFrom(matrix);
  18344. return this;
  18345. };
  18346. /**
  18347. * Returns the mesh Pose matrix.
  18348. * Returned object : Matrix
  18349. */
  18350. TransformNode.prototype.getPoseMatrix = function () {
  18351. return this._poseMatrix;
  18352. };
  18353. TransformNode.prototype._isSynchronized = function () {
  18354. if (this._isDirty) {
  18355. return false;
  18356. }
  18357. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18358. return false;
  18359. if (this._cache.pivotMatrixUpdated) {
  18360. return false;
  18361. }
  18362. if (this.infiniteDistance) {
  18363. return false;
  18364. }
  18365. if (!this._cache.position.equals(this.position))
  18366. return false;
  18367. if (this.rotationQuaternion) {
  18368. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18369. return false;
  18370. }
  18371. if (!this._cache.rotation.equals(this.rotation))
  18372. return false;
  18373. if (!this._cache.scaling.equals(this.scaling))
  18374. return false;
  18375. return true;
  18376. };
  18377. TransformNode.prototype._initCache = function () {
  18378. _super.prototype._initCache.call(this);
  18379. this._cache.localMatrixUpdated = false;
  18380. this._cache.position = BABYLON.Vector3.Zero();
  18381. this._cache.scaling = BABYLON.Vector3.Zero();
  18382. this._cache.rotation = BABYLON.Vector3.Zero();
  18383. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18384. this._cache.billboardMode = -1;
  18385. };
  18386. TransformNode.prototype.markAsDirty = function (property) {
  18387. if (property === "rotation") {
  18388. this.rotationQuaternion = null;
  18389. }
  18390. this._currentRenderId = Number.MAX_VALUE;
  18391. this._isDirty = true;
  18392. return this;
  18393. };
  18394. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18395. /**
  18396. * Returns the current mesh absolute position.
  18397. * Retuns a Vector3.
  18398. */
  18399. get: function () {
  18400. return this._absolutePosition;
  18401. },
  18402. enumerable: true,
  18403. configurable: true
  18404. });
  18405. /**
  18406. * Sets a new matrix to apply before all other transformation
  18407. * @param matrix defines the transform matrix
  18408. * @returns the current TransformNode
  18409. */
  18410. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18411. return this.setPivotMatrix(matrix, false);
  18412. };
  18413. /**
  18414. * Sets a new pivot matrix to the current node
  18415. * @param matrix defines the new pivot matrix to use
  18416. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  18417. * @returns the current TransformNode
  18418. */
  18419. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18420. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18421. this._pivotMatrix = matrix.clone();
  18422. this._cache.pivotMatrixUpdated = true;
  18423. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18424. if (this._postMultiplyPivotMatrix) {
  18425. if (!this._pivotMatrixInverse) {
  18426. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18427. }
  18428. else {
  18429. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18430. }
  18431. }
  18432. return this;
  18433. };
  18434. /**
  18435. * Returns the mesh pivot matrix.
  18436. * Default : Identity.
  18437. * A Matrix is returned.
  18438. */
  18439. TransformNode.prototype.getPivotMatrix = function () {
  18440. return this._pivotMatrix;
  18441. };
  18442. /**
  18443. * Prevents the World matrix to be computed any longer.
  18444. * Returns the TransformNode.
  18445. */
  18446. TransformNode.prototype.freezeWorldMatrix = function () {
  18447. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18448. this.computeWorldMatrix(true);
  18449. this._isWorldMatrixFrozen = true;
  18450. return this;
  18451. };
  18452. /**
  18453. * Allows back the World matrix computation.
  18454. * Returns the TransformNode.
  18455. */
  18456. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18457. this._isWorldMatrixFrozen = false;
  18458. this.computeWorldMatrix(true);
  18459. return this;
  18460. };
  18461. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18462. /**
  18463. * True if the World matrix has been frozen.
  18464. * Returns a boolean.
  18465. */
  18466. get: function () {
  18467. return this._isWorldMatrixFrozen;
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. /**
  18473. * Retuns the mesh absolute position in the World.
  18474. * Returns a Vector3.
  18475. */
  18476. TransformNode.prototype.getAbsolutePosition = function () {
  18477. this.computeWorldMatrix();
  18478. return this._absolutePosition;
  18479. };
  18480. /**
  18481. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18482. * Returns the TransformNode.
  18483. */
  18484. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18485. if (!absolutePosition) {
  18486. return this;
  18487. }
  18488. var absolutePositionX;
  18489. var absolutePositionY;
  18490. var absolutePositionZ;
  18491. if (absolutePosition.x === undefined) {
  18492. if (arguments.length < 3) {
  18493. return this;
  18494. }
  18495. absolutePositionX = arguments[0];
  18496. absolutePositionY = arguments[1];
  18497. absolutePositionZ = arguments[2];
  18498. }
  18499. else {
  18500. absolutePositionX = absolutePosition.x;
  18501. absolutePositionY = absolutePosition.y;
  18502. absolutePositionZ = absolutePosition.z;
  18503. }
  18504. if (this.parent) {
  18505. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18506. invertParentWorldMatrix.invert();
  18507. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18508. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18509. }
  18510. else {
  18511. this.position.x = absolutePositionX;
  18512. this.position.y = absolutePositionY;
  18513. this.position.z = absolutePositionZ;
  18514. }
  18515. return this;
  18516. };
  18517. /**
  18518. * Sets the mesh position in its local space.
  18519. * Returns the TransformNode.
  18520. */
  18521. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18522. this.computeWorldMatrix();
  18523. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18524. return this;
  18525. };
  18526. /**
  18527. * Returns the mesh position in the local space from the current World matrix values.
  18528. * Returns a new Vector3.
  18529. */
  18530. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18531. this.computeWorldMatrix();
  18532. var invLocalWorldMatrix = this._localWorld.clone();
  18533. invLocalWorldMatrix.invert();
  18534. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18535. };
  18536. /**
  18537. * Translates the mesh along the passed Vector3 in its local space.
  18538. * Returns the TransformNode.
  18539. */
  18540. TransformNode.prototype.locallyTranslate = function (vector3) {
  18541. this.computeWorldMatrix(true);
  18542. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18543. return this;
  18544. };
  18545. /**
  18546. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18547. * @param targetPoint the position (must be in same space as current mesh) to look at
  18548. * @param yawCor optional yaw (y-axis) correction in radians
  18549. * @param pitchCor optional pitch (x-axis) correction in radians
  18550. * @param rollCor optional roll (z-axis) correction in radians
  18551. * @param space the choosen space of the target
  18552. * @returns the TransformNode.
  18553. */
  18554. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18555. if (yawCor === void 0) { yawCor = 0; }
  18556. if (pitchCor === void 0) { pitchCor = 0; }
  18557. if (rollCor === void 0) { rollCor = 0; }
  18558. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18559. var dv = TransformNode._lookAtVectorCache;
  18560. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18561. targetPoint.subtractToRef(pos, dv);
  18562. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18563. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18564. var pitch = Math.atan2(dv.y, len);
  18565. if (this.rotationQuaternion) {
  18566. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18567. }
  18568. else {
  18569. this.rotation.x = pitch + pitchCor;
  18570. this.rotation.y = yaw + yawCor;
  18571. this.rotation.z = rollCor;
  18572. }
  18573. return this;
  18574. };
  18575. /**
  18576. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18577. * This Vector3 is expressed in the World space.
  18578. */
  18579. TransformNode.prototype.getDirection = function (localAxis) {
  18580. var result = BABYLON.Vector3.Zero();
  18581. this.getDirectionToRef(localAxis, result);
  18582. return result;
  18583. };
  18584. /**
  18585. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18586. * localAxis is expressed in the mesh local space.
  18587. * result is computed in the Wordl space from the mesh World matrix.
  18588. * Returns the TransformNode.
  18589. */
  18590. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18591. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18592. return this;
  18593. };
  18594. /**
  18595. * Sets a new pivot point to the current node
  18596. * @param point defines the new pivot point to use
  18597. * @param space defines if the point is in world or local space (local by default)
  18598. * @returns the current TransformNode
  18599. */
  18600. TransformNode.prototype.setPivotPoint = function (point, space) {
  18601. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18602. if (this.getScene().getRenderId() == 0) {
  18603. this.computeWorldMatrix(true);
  18604. }
  18605. var wm = this.getWorldMatrix();
  18606. if (space == BABYLON.Space.WORLD) {
  18607. var tmat = BABYLON.Tmp.Matrix[0];
  18608. wm.invertToRef(tmat);
  18609. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18610. }
  18611. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18612. };
  18613. /**
  18614. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18615. */
  18616. TransformNode.prototype.getPivotPoint = function () {
  18617. var point = BABYLON.Vector3.Zero();
  18618. this.getPivotPointToRef(point);
  18619. return point;
  18620. };
  18621. /**
  18622. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18623. * Returns the TransformNode.
  18624. */
  18625. TransformNode.prototype.getPivotPointToRef = function (result) {
  18626. result.x = -this._pivotMatrix.m[12];
  18627. result.y = -this._pivotMatrix.m[13];
  18628. result.z = -this._pivotMatrix.m[14];
  18629. return this;
  18630. };
  18631. /**
  18632. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18633. */
  18634. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18635. var point = BABYLON.Vector3.Zero();
  18636. this.getAbsolutePivotPointToRef(point);
  18637. return point;
  18638. };
  18639. /**
  18640. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18641. * Returns the TransformNode.
  18642. */
  18643. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18644. result.x = this._pivotMatrix.m[12];
  18645. result.y = this._pivotMatrix.m[13];
  18646. result.z = this._pivotMatrix.m[14];
  18647. this.getPivotPointToRef(result);
  18648. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18649. return this;
  18650. };
  18651. /**
  18652. * Defines the passed node as the parent of the current node.
  18653. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18654. * Returns the TransformNode.
  18655. */
  18656. TransformNode.prototype.setParent = function (node) {
  18657. if (!node && !this.parent) {
  18658. return this;
  18659. }
  18660. if (!node) {
  18661. var rotation = BABYLON.Tmp.Quaternion[0];
  18662. var position = BABYLON.Tmp.Vector3[0];
  18663. var scale = BABYLON.Tmp.Vector3[1];
  18664. if (this.parent && this.parent.computeWorldMatrix) {
  18665. this.parent.computeWorldMatrix(true);
  18666. }
  18667. this.computeWorldMatrix(true);
  18668. this.getWorldMatrix().decompose(scale, rotation, position);
  18669. if (this.rotationQuaternion) {
  18670. this.rotationQuaternion.copyFrom(rotation);
  18671. }
  18672. else {
  18673. rotation.toEulerAnglesToRef(this.rotation);
  18674. }
  18675. this.scaling.x = scale.x;
  18676. this.scaling.y = scale.y;
  18677. this.scaling.z = scale.z;
  18678. this.position.x = position.x;
  18679. this.position.y = position.y;
  18680. this.position.z = position.z;
  18681. }
  18682. else {
  18683. var rotation = BABYLON.Tmp.Quaternion[0];
  18684. var position = BABYLON.Tmp.Vector3[0];
  18685. var scale = BABYLON.Tmp.Vector3[1];
  18686. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18687. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18688. this.computeWorldMatrix(true);
  18689. node.computeWorldMatrix(true);
  18690. node.getWorldMatrix().invertToRef(invParentMatrix);
  18691. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18692. diffMatrix.decompose(scale, rotation, position);
  18693. if (this.rotationQuaternion) {
  18694. this.rotationQuaternion.copyFrom(rotation);
  18695. }
  18696. else {
  18697. rotation.toEulerAnglesToRef(this.rotation);
  18698. }
  18699. this.position.x = position.x;
  18700. this.position.y = position.y;
  18701. this.position.z = position.z;
  18702. this.scaling.x = scale.x;
  18703. this.scaling.y = scale.y;
  18704. this.scaling.z = scale.z;
  18705. }
  18706. this.parent = node;
  18707. return this;
  18708. };
  18709. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18710. get: function () {
  18711. return this._nonUniformScaling;
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18717. if (this._nonUniformScaling === value) {
  18718. return false;
  18719. }
  18720. this._nonUniformScaling = value;
  18721. return true;
  18722. };
  18723. /**
  18724. * Attach the current TransformNode to another TransformNode associated with a bone
  18725. * @param bone Bone affecting the TransformNode
  18726. * @param affectedTransformNode TransformNode associated with the bone
  18727. */
  18728. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18729. this._transformToBoneReferal = affectedTransformNode;
  18730. this.parent = bone;
  18731. if (bone.getWorldMatrix().determinant() < 0) {
  18732. this.scalingDeterminant *= -1;
  18733. }
  18734. return this;
  18735. };
  18736. TransformNode.prototype.detachFromBone = function () {
  18737. if (!this.parent) {
  18738. return this;
  18739. }
  18740. if (this.parent.getWorldMatrix().determinant() < 0) {
  18741. this.scalingDeterminant *= -1;
  18742. }
  18743. this._transformToBoneReferal = null;
  18744. this.parent = null;
  18745. return this;
  18746. };
  18747. /**
  18748. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18749. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18750. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18751. * The passed axis is also normalized.
  18752. * Returns the TransformNode.
  18753. */
  18754. TransformNode.prototype.rotate = function (axis, amount, space) {
  18755. axis.normalize();
  18756. if (!this.rotationQuaternion) {
  18757. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18758. this.rotation = BABYLON.Vector3.Zero();
  18759. }
  18760. var rotationQuaternion;
  18761. if (!space || space === BABYLON.Space.LOCAL) {
  18762. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18763. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18764. }
  18765. else {
  18766. if (this.parent) {
  18767. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18768. invertParentWorldMatrix.invert();
  18769. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18770. }
  18771. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18772. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18773. }
  18774. return this;
  18775. };
  18776. /**
  18777. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18778. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18779. * The passed axis is also normalized.
  18780. * Returns the TransformNode.
  18781. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18782. */
  18783. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18784. axis.normalize();
  18785. if (!this.rotationQuaternion) {
  18786. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18787. this.rotation.copyFromFloats(0, 0, 0);
  18788. }
  18789. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18790. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18791. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18792. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18793. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18794. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18795. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18796. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18797. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18798. return this;
  18799. };
  18800. /**
  18801. * Translates the mesh along the axis vector for the passed distance in the given space.
  18802. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18803. * Returns the TransformNode.
  18804. */
  18805. TransformNode.prototype.translate = function (axis, distance, space) {
  18806. var displacementVector = axis.scale(distance);
  18807. if (!space || space === BABYLON.Space.LOCAL) {
  18808. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18809. this.setPositionWithLocalVector(tempV3);
  18810. }
  18811. else {
  18812. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18813. }
  18814. return this;
  18815. };
  18816. /**
  18817. * Adds a rotation step to the mesh current rotation.
  18818. * x, y, z are Euler angles expressed in radians.
  18819. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18820. * This means this rotation is made in the mesh local space only.
  18821. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18822. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18823. * ```javascript
  18824. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18825. * ```
  18826. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18827. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  18828. * Returns the TransformNode.
  18829. */
  18830. TransformNode.prototype.addRotation = function (x, y, z) {
  18831. var rotationQuaternion;
  18832. if (this.rotationQuaternion) {
  18833. rotationQuaternion = this.rotationQuaternion;
  18834. }
  18835. else {
  18836. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18837. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18838. }
  18839. var accumulation = BABYLON.Tmp.Quaternion[0];
  18840. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18841. rotationQuaternion.multiplyInPlace(accumulation);
  18842. if (!this.rotationQuaternion) {
  18843. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18844. }
  18845. return this;
  18846. };
  18847. /**
  18848. * Computes the mesh World matrix and returns it.
  18849. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18850. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18851. * If the parameter `force`is set to `true`, the actual computation is done.
  18852. * Returns the mesh World Matrix.
  18853. */
  18854. TransformNode.prototype.computeWorldMatrix = function (force) {
  18855. if (this._isWorldMatrixFrozen) {
  18856. return this._worldMatrix;
  18857. }
  18858. if (!force && this.isSynchronized(true)) {
  18859. this._currentRenderId = this.getScene().getRenderId();
  18860. return this._worldMatrix;
  18861. }
  18862. this._cache.position.copyFrom(this.position);
  18863. this._cache.scaling.copyFrom(this.scaling);
  18864. this._cache.pivotMatrixUpdated = false;
  18865. this._cache.billboardMode = this.billboardMode;
  18866. this._currentRenderId = this.getScene().getRenderId();
  18867. this._childRenderId = this.getScene().getRenderId();
  18868. this._isDirty = false;
  18869. // Scaling
  18870. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18871. // Rotation
  18872. //rotate, if quaternion is set and rotation was used
  18873. if (this.rotationQuaternion) {
  18874. var len = this.rotation.length();
  18875. if (len) {
  18876. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18877. this.rotation.copyFromFloats(0, 0, 0);
  18878. }
  18879. }
  18880. if (this.rotationQuaternion) {
  18881. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18882. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18883. }
  18884. else {
  18885. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18886. this._cache.rotation.copyFrom(this.rotation);
  18887. }
  18888. // Translation
  18889. var camera = this.getScene().activeCamera;
  18890. if (this.infiniteDistance && !this.parent && camera) {
  18891. var cameraWorldMatrix = camera.getWorldMatrix();
  18892. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18893. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18894. }
  18895. else {
  18896. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18897. }
  18898. // Composing transformations
  18899. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18900. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18901. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18902. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18903. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18904. // Need to decompose each rotation here
  18905. var currentPosition = BABYLON.Tmp.Vector3[3];
  18906. if (this.parent && this.parent.getWorldMatrix) {
  18907. if (this._transformToBoneReferal) {
  18908. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18909. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18910. }
  18911. else {
  18912. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18913. }
  18914. }
  18915. else {
  18916. currentPosition.copyFrom(this.position);
  18917. }
  18918. currentPosition.subtractInPlace(camera.globalPosition);
  18919. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18920. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18921. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18922. }
  18923. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18924. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18925. }
  18926. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18927. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18928. }
  18929. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18930. }
  18931. else {
  18932. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18933. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18934. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18935. }
  18936. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18937. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18938. }
  18939. // Post multiply inverse of pivotMatrix
  18940. if (this._postMultiplyPivotMatrix) {
  18941. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  18942. }
  18943. // Local world
  18944. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18945. // Parent
  18946. if (this.parent && this.parent.getWorldMatrix) {
  18947. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18948. if (this._transformToBoneReferal) {
  18949. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18950. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18951. }
  18952. else {
  18953. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18954. }
  18955. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18956. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18957. this._worldMatrix.copyFrom(this._localWorld);
  18958. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18959. }
  18960. else {
  18961. if (this._transformToBoneReferal) {
  18962. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18963. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18964. }
  18965. else {
  18966. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18967. }
  18968. }
  18969. this._markSyncedWithParent();
  18970. }
  18971. else {
  18972. this._worldMatrix.copyFrom(this._localWorld);
  18973. }
  18974. // Normal matrix
  18975. if (!this.ignoreNonUniformScaling) {
  18976. if (this.scaling.isNonUniform) {
  18977. this._updateNonUniformScalingState(true);
  18978. }
  18979. else if (this.parent && this.parent._nonUniformScaling) {
  18980. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18981. }
  18982. else {
  18983. this._updateNonUniformScalingState(false);
  18984. }
  18985. }
  18986. else {
  18987. this._updateNonUniformScalingState(false);
  18988. }
  18989. this._afterComputeWorldMatrix();
  18990. // Absolute position
  18991. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18992. // Callbacks
  18993. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18994. if (!this._poseMatrix) {
  18995. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18996. }
  18997. // Cache the determinant
  18998. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18999. return this._worldMatrix;
  19000. };
  19001. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19002. };
  19003. /**
  19004. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19005. * @param func: callback function to add
  19006. *
  19007. * Returns the TransformNode.
  19008. */
  19009. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19010. this.onAfterWorldMatrixUpdateObservable.add(func);
  19011. return this;
  19012. };
  19013. /**
  19014. * Removes a registered callback function.
  19015. * Returns the TransformNode.
  19016. */
  19017. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19018. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19019. return this;
  19020. };
  19021. /**
  19022. * Clone the current transform node
  19023. * Returns the new transform node
  19024. * @param name Name of the new clone
  19025. * @param newParent New parent for the clone
  19026. * @param doNotCloneChildren Do not clone children hierarchy
  19027. */
  19028. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19029. var _this = this;
  19030. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19031. result.name = name;
  19032. result.id = name;
  19033. if (newParent) {
  19034. result.parent = newParent;
  19035. }
  19036. if (!doNotCloneChildren) {
  19037. // Children
  19038. var directDescendants = this.getDescendants(true);
  19039. for (var index = 0; index < directDescendants.length; index++) {
  19040. var child = directDescendants[index];
  19041. if (child.clone) {
  19042. child.clone(name + "." + child.name, result);
  19043. }
  19044. }
  19045. }
  19046. return result;
  19047. };
  19048. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19049. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19050. serializationObject.type = this.getClassName();
  19051. // Parent
  19052. if (this.parent) {
  19053. serializationObject.parentId = this.parent.id;
  19054. }
  19055. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19056. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19057. }
  19058. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19059. serializationObject.isEnabled = this.isEnabled();
  19060. // Parent
  19061. if (this.parent) {
  19062. serializationObject.parentId = this.parent.id;
  19063. }
  19064. return serializationObject;
  19065. };
  19066. // Statics
  19067. /**
  19068. * Returns a new TransformNode object parsed from the source provided.
  19069. * The parameter `parsedMesh` is the source.
  19070. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19071. */
  19072. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19073. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19074. if (BABYLON.Tags) {
  19075. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19076. }
  19077. if (parsedTransformNode.localMatrix) {
  19078. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19079. }
  19080. else if (parsedTransformNode.pivotMatrix) {
  19081. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19082. }
  19083. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19084. // Parent
  19085. if (parsedTransformNode.parentId) {
  19086. transformNode._waitingParentId = parsedTransformNode.parentId;
  19087. }
  19088. return transformNode;
  19089. };
  19090. /**
  19091. * Releases resources associated with this transform node.
  19092. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19093. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19094. */
  19095. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19096. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19097. // Animations
  19098. this.getScene().stopAnimation(this);
  19099. // Remove from scene
  19100. this.getScene().removeTransformNode(this);
  19101. this.onAfterWorldMatrixUpdateObservable.clear();
  19102. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19103. };
  19104. // Statics
  19105. TransformNode.BILLBOARDMODE_NONE = 0;
  19106. TransformNode.BILLBOARDMODE_X = 1;
  19107. TransformNode.BILLBOARDMODE_Y = 2;
  19108. TransformNode.BILLBOARDMODE_Z = 4;
  19109. TransformNode.BILLBOARDMODE_ALL = 7;
  19110. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19111. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19112. __decorate([
  19113. BABYLON.serializeAsVector3()
  19114. ], TransformNode.prototype, "_rotation", void 0);
  19115. __decorate([
  19116. BABYLON.serializeAsQuaternion()
  19117. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19118. __decorate([
  19119. BABYLON.serializeAsVector3()
  19120. ], TransformNode.prototype, "_scaling", void 0);
  19121. __decorate([
  19122. BABYLON.serialize()
  19123. ], TransformNode.prototype, "billboardMode", void 0);
  19124. __decorate([
  19125. BABYLON.serialize()
  19126. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19127. __decorate([
  19128. BABYLON.serialize()
  19129. ], TransformNode.prototype, "infiniteDistance", void 0);
  19130. __decorate([
  19131. BABYLON.serialize()
  19132. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19133. __decorate([
  19134. BABYLON.serializeAsVector3()
  19135. ], TransformNode.prototype, "position", void 0);
  19136. return TransformNode;
  19137. }(BABYLON.Node));
  19138. BABYLON.TransformNode = TransformNode;
  19139. })(BABYLON || (BABYLON = {}));
  19140. //# sourceMappingURL=babylon.transformNode.js.map
  19141. var BABYLON;
  19142. (function (BABYLON) {
  19143. /**
  19144. * Class used to store all common mesh properties
  19145. */
  19146. var AbstractMesh = /** @class */ (function (_super) {
  19147. __extends(AbstractMesh, _super);
  19148. // Constructor
  19149. /**
  19150. * Creates a new AbstractMesh
  19151. * @param name defines the name of the mesh
  19152. * @param scene defines the hosting scene
  19153. */
  19154. function AbstractMesh(name, scene) {
  19155. if (scene === void 0) { scene = null; }
  19156. var _this = _super.call(this, name, scene, false) || this;
  19157. _this._facetNb = 0; // facet number
  19158. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19159. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19160. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19161. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19162. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19163. _this._subDiv = {
  19164. max: 1,
  19165. X: 1,
  19166. Y: 1,
  19167. Z: 1
  19168. };
  19169. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19170. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19171. // Events
  19172. /**
  19173. * An event triggered when this mesh collides with another one
  19174. */
  19175. _this.onCollideObservable = new BABYLON.Observable();
  19176. /**
  19177. * An event triggered when the collision's position changes
  19178. */
  19179. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19180. /**
  19181. * An event triggered when material is changed
  19182. */
  19183. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19184. // Properties
  19185. /**
  19186. * Gets or sets the orientation for POV movement & rotation
  19187. */
  19188. _this.definedFacingForward = true;
  19189. /**
  19190. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19191. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19192. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19193. * @see http://doc.babylonjs.com/features/occlusionquery
  19194. */
  19195. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19196. /**
  19197. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19198. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19199. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19200. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19201. * @see http://doc.babylonjs.com/features/occlusionquery
  19202. */
  19203. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19204. /**
  19205. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19206. * The default value is -1 which means don't break the query and wait till the result
  19207. * @see http://doc.babylonjs.com/features/occlusionquery
  19208. */
  19209. _this.occlusionRetryCount = -1;
  19210. /** @hidden */
  19211. _this._occlusionInternalRetryCounter = 0;
  19212. /** @hidden */
  19213. _this._isOccluded = false;
  19214. /** @hidden */
  19215. _this._isOcclusionQueryInProgress = false;
  19216. _this._visibility = 1.0;
  19217. /** Gets or sets the alpha index used to sort transparent meshes
  19218. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19219. */
  19220. _this.alphaIndex = Number.MAX_VALUE;
  19221. /**
  19222. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19223. */
  19224. _this.isVisible = true;
  19225. /**
  19226. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19227. */
  19228. _this.isPickable = true;
  19229. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19230. _this.showSubMeshesBoundingBox = false;
  19231. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19232. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19233. */
  19234. _this.isBlocker = false;
  19235. /**
  19236. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19237. */
  19238. _this.enablePointerMoveEvents = false;
  19239. /**
  19240. * Specifies the rendering group id for this mesh (0 by default)
  19241. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19242. */
  19243. _this.renderingGroupId = 0;
  19244. _this._receiveShadows = false;
  19245. /**
  19246. * Gets or sets a boolean indicating if the outline must be rendered as well
  19247. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19248. */
  19249. _this.renderOutline = false;
  19250. /** Defines color to use when rendering outline */
  19251. _this.outlineColor = BABYLON.Color3.Red();
  19252. /** Define width to use when rendering outline */
  19253. _this.outlineWidth = 0.02;
  19254. /**
  19255. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19256. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19257. */
  19258. _this.renderOverlay = false;
  19259. /** Defines color to use when rendering overlay */
  19260. _this.overlayColor = BABYLON.Color3.Red();
  19261. /** Defines alpha to use when rendering overlay */
  19262. _this.overlayAlpha = 0.5;
  19263. _this._hasVertexAlpha = false;
  19264. _this._useVertexColors = true;
  19265. _this._computeBonesUsingShaders = true;
  19266. _this._numBoneInfluencers = 4;
  19267. _this._applyFog = true;
  19268. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19269. _this.useOctreeForRenderingSelection = true;
  19270. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19271. _this.useOctreeForPicking = true;
  19272. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19273. _this.useOctreeForCollisions = true;
  19274. _this._layerMask = 0x0FFFFFFF;
  19275. /**
  19276. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19277. */
  19278. _this.alwaysSelectAsActiveMesh = false;
  19279. /**
  19280. * Gets or sets the current action manager
  19281. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19282. */
  19283. _this.actionManager = null;
  19284. /**
  19285. * Gets or sets impostor used for physic simulation
  19286. * @see http://doc.babylonjs.com/features/physics_engine
  19287. */
  19288. _this.physicsImpostor = null;
  19289. // Collisions
  19290. _this._checkCollisions = false;
  19291. _this._collisionMask = -1;
  19292. _this._collisionGroup = -1;
  19293. /**
  19294. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19295. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19296. */
  19297. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19298. /**
  19299. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19300. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19301. */
  19302. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19303. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19304. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19305. // Edges
  19306. /**
  19307. * Defines edge width used when edgesRenderer is enabled
  19308. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19309. */
  19310. _this.edgesWidth = 1;
  19311. /**
  19312. * Defines edge color used when edgesRenderer is enabled
  19313. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19314. */
  19315. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19316. // Cache
  19317. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19318. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19319. /** @hidden */
  19320. _this._renderId = 0;
  19321. /** @hidden */
  19322. _this._intersectionsInProgress = new Array();
  19323. /** @hidden */
  19324. _this._unIndexed = false;
  19325. /** @hidden */
  19326. _this._lightSources = new Array();
  19327. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19328. if (collidedMesh === void 0) { collidedMesh = null; }
  19329. //TODO move this to the collision coordinator!
  19330. if (_this.getScene().workerCollisions)
  19331. newPosition.multiplyInPlace(_this._collider._radius);
  19332. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19333. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19334. _this.position.addInPlace(_this._diffPositionForCollisions);
  19335. }
  19336. if (collidedMesh) {
  19337. _this.onCollideObservable.notifyObservers(collidedMesh);
  19338. }
  19339. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19340. };
  19341. _this.getScene().addMesh(_this);
  19342. _this._resyncLightSources();
  19343. return _this;
  19344. }
  19345. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19346. /**
  19347. * No billboard
  19348. */
  19349. get: function () {
  19350. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19351. },
  19352. enumerable: true,
  19353. configurable: true
  19354. });
  19355. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19356. /** Billboard on X axis */
  19357. get: function () {
  19358. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19359. },
  19360. enumerable: true,
  19361. configurable: true
  19362. });
  19363. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19364. /** Billboard on Y axis */
  19365. get: function () {
  19366. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19367. },
  19368. enumerable: true,
  19369. configurable: true
  19370. });
  19371. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19372. /** Billboard on Z axis */
  19373. get: function () {
  19374. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19380. /** Billboard on all axes */
  19381. get: function () {
  19382. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19383. },
  19384. enumerable: true,
  19385. configurable: true
  19386. });
  19387. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19388. /**
  19389. * Gets the number of facets in the mesh
  19390. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19391. */
  19392. get: function () {
  19393. return this._facetNb;
  19394. },
  19395. enumerable: true,
  19396. configurable: true
  19397. });
  19398. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19399. /**
  19400. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19401. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19402. */
  19403. get: function () {
  19404. return this._partitioningSubdivisions;
  19405. },
  19406. set: function (nb) {
  19407. this._partitioningSubdivisions = nb;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19413. /**
  19414. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19415. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19416. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19417. */
  19418. get: function () {
  19419. return this._partitioningBBoxRatio;
  19420. },
  19421. set: function (ratio) {
  19422. this._partitioningBBoxRatio = ratio;
  19423. },
  19424. enumerable: true,
  19425. configurable: true
  19426. });
  19427. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19428. /**
  19429. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19430. * Works only for updatable meshes.
  19431. * Doesn't work with multi-materials
  19432. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19433. */
  19434. get: function () {
  19435. return this._facetDepthSort;
  19436. },
  19437. set: function (sort) {
  19438. this._facetDepthSort = sort;
  19439. },
  19440. enumerable: true,
  19441. configurable: true
  19442. });
  19443. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19444. /**
  19445. * The location (Vector3) where the facet depth sort must be computed from.
  19446. * By default, the active camera position.
  19447. * Used only when facet depth sort is enabled
  19448. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19449. */
  19450. get: function () {
  19451. return this._facetDepthSortFrom;
  19452. },
  19453. set: function (location) {
  19454. this._facetDepthSortFrom = location;
  19455. },
  19456. enumerable: true,
  19457. configurable: true
  19458. });
  19459. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19460. /**
  19461. * gets a boolean indicating if facetData is enabled
  19462. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19463. */
  19464. get: function () {
  19465. return this._facetDataEnabled;
  19466. },
  19467. enumerable: true,
  19468. configurable: true
  19469. });
  19470. /** @hidden */
  19471. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19472. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19473. return false;
  19474. }
  19475. this._markSubMeshesAsMiscDirty();
  19476. return true;
  19477. };
  19478. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19479. /** Set a function to call when this mesh collides with another one */
  19480. set: function (callback) {
  19481. if (this._onCollideObserver) {
  19482. this.onCollideObservable.remove(this._onCollideObserver);
  19483. }
  19484. this._onCollideObserver = this.onCollideObservable.add(callback);
  19485. },
  19486. enumerable: true,
  19487. configurable: true
  19488. });
  19489. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19490. /** Set a function to call when the collision's position changes */
  19491. set: function (callback) {
  19492. if (this._onCollisionPositionChangeObserver) {
  19493. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19494. }
  19495. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19496. },
  19497. enumerable: true,
  19498. configurable: true
  19499. });
  19500. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19501. /**
  19502. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19503. * @see http://doc.babylonjs.com/features/occlusionquery
  19504. */
  19505. get: function () {
  19506. return this._isOccluded;
  19507. },
  19508. set: function (value) {
  19509. this._isOccluded = value;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19515. /**
  19516. * Flag to check the progress status of the query
  19517. * @see http://doc.babylonjs.com/features/occlusionquery
  19518. */
  19519. get: function () {
  19520. return this._isOcclusionQueryInProgress;
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19526. /**
  19527. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19528. */
  19529. get: function () {
  19530. return this._visibility;
  19531. },
  19532. /**
  19533. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19534. */
  19535. set: function (value) {
  19536. if (this._visibility === value) {
  19537. return;
  19538. }
  19539. this._visibility = value;
  19540. this._markSubMeshesAsMiscDirty();
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(AbstractMesh.prototype, "material", {
  19546. /** Gets or sets current material */
  19547. get: function () {
  19548. return this._material;
  19549. },
  19550. set: function (value) {
  19551. if (this._material === value) {
  19552. return;
  19553. }
  19554. this._material = value;
  19555. if (this.onMaterialChangedObservable.hasObservers) {
  19556. this.onMaterialChangedObservable.notifyObservers(this);
  19557. }
  19558. if (!this.subMeshes) {
  19559. return;
  19560. }
  19561. this._unBindEffect();
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19567. /**
  19568. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19569. * @see http://doc.babylonjs.com/babylon101/shadows
  19570. */
  19571. get: function () {
  19572. return this._receiveShadows;
  19573. },
  19574. set: function (value) {
  19575. if (this._receiveShadows === value) {
  19576. return;
  19577. }
  19578. this._receiveShadows = value;
  19579. this._markSubMeshesAsLightDirty();
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19585. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19586. get: function () {
  19587. return this._hasVertexAlpha;
  19588. },
  19589. set: function (value) {
  19590. if (this._hasVertexAlpha === value) {
  19591. return;
  19592. }
  19593. this._hasVertexAlpha = value;
  19594. this._markSubMeshesAsAttributesDirty();
  19595. this._markSubMeshesAsMiscDirty();
  19596. },
  19597. enumerable: true,
  19598. configurable: true
  19599. });
  19600. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19601. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19602. get: function () {
  19603. return this._useVertexColors;
  19604. },
  19605. set: function (value) {
  19606. if (this._useVertexColors === value) {
  19607. return;
  19608. }
  19609. this._useVertexColors = value;
  19610. this._markSubMeshesAsAttributesDirty();
  19611. },
  19612. enumerable: true,
  19613. configurable: true
  19614. });
  19615. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19616. /**
  19617. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19618. */
  19619. get: function () {
  19620. return this._computeBonesUsingShaders;
  19621. },
  19622. set: function (value) {
  19623. if (this._computeBonesUsingShaders === value) {
  19624. return;
  19625. }
  19626. this._computeBonesUsingShaders = value;
  19627. this._markSubMeshesAsAttributesDirty();
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19633. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19634. get: function () {
  19635. return this._numBoneInfluencers;
  19636. },
  19637. set: function (value) {
  19638. if (this._numBoneInfluencers === value) {
  19639. return;
  19640. }
  19641. this._numBoneInfluencers = value;
  19642. this._markSubMeshesAsAttributesDirty();
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19648. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19649. get: function () {
  19650. return this._applyFog;
  19651. },
  19652. set: function (value) {
  19653. if (this._applyFog === value) {
  19654. return;
  19655. }
  19656. this._applyFog = value;
  19657. this._markSubMeshesAsMiscDirty();
  19658. },
  19659. enumerable: true,
  19660. configurable: true
  19661. });
  19662. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19663. /**
  19664. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19665. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19666. */
  19667. get: function () {
  19668. return this._layerMask;
  19669. },
  19670. set: function (value) {
  19671. if (value === this._layerMask) {
  19672. return;
  19673. }
  19674. this._layerMask = value;
  19675. this._resyncLightSources();
  19676. },
  19677. enumerable: true,
  19678. configurable: true
  19679. });
  19680. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19681. /**
  19682. * Gets or sets a collision mask used to mask collisions (default is -1).
  19683. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19684. */
  19685. get: function () {
  19686. return this._collisionMask;
  19687. },
  19688. set: function (mask) {
  19689. this._collisionMask = !isNaN(mask) ? mask : -1;
  19690. },
  19691. enumerable: true,
  19692. configurable: true
  19693. });
  19694. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19695. /**
  19696. * Gets or sets the current collision group mask (-1 by default).
  19697. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19698. */
  19699. get: function () {
  19700. return this._collisionGroup;
  19701. },
  19702. set: function (mask) {
  19703. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19709. /** @hidden */
  19710. get: function () {
  19711. return null;
  19712. },
  19713. enumerable: true,
  19714. configurable: true
  19715. });
  19716. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19717. get: function () {
  19718. return this._skeleton;
  19719. },
  19720. /**
  19721. * Gets or sets a skeleton to apply skining transformations
  19722. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19723. */
  19724. set: function (value) {
  19725. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19726. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19727. }
  19728. if (value && value.needInitialSkinMatrix) {
  19729. value._registerMeshWithPoseMatrix(this);
  19730. }
  19731. this._skeleton = value;
  19732. if (!this._skeleton) {
  19733. this._bonesTransformMatrices = null;
  19734. }
  19735. this._markSubMeshesAsAttributesDirty();
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. /**
  19741. * Returns the string "AbstractMesh"
  19742. * @returns "AbstractMesh"
  19743. */
  19744. AbstractMesh.prototype.getClassName = function () {
  19745. return "AbstractMesh";
  19746. };
  19747. /**
  19748. * Gets a string representation of the current mesh
  19749. * @param fullDetails defines a boolean indicating if full details must be included
  19750. * @returns a string representation of the current mesh
  19751. */
  19752. AbstractMesh.prototype.toString = function (fullDetails) {
  19753. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19754. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19755. if (this._skeleton) {
  19756. ret += ", skeleton: " + this._skeleton.name;
  19757. }
  19758. if (fullDetails) {
  19759. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19760. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19761. }
  19762. return ret;
  19763. };
  19764. /** @hidden */
  19765. AbstractMesh.prototype._rebuild = function () {
  19766. if (this._occlusionQuery) {
  19767. this._occlusionQuery = null;
  19768. }
  19769. if (this._edgesRenderer) {
  19770. this._edgesRenderer._rebuild();
  19771. }
  19772. if (!this.subMeshes) {
  19773. return;
  19774. }
  19775. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19776. var subMesh = _a[_i];
  19777. subMesh._rebuild();
  19778. }
  19779. };
  19780. /** @hidden */
  19781. AbstractMesh.prototype._resyncLightSources = function () {
  19782. this._lightSources.length = 0;
  19783. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19784. var light = _a[_i];
  19785. if (!light.isEnabled()) {
  19786. continue;
  19787. }
  19788. if (light.canAffectMesh(this)) {
  19789. this._lightSources.push(light);
  19790. }
  19791. }
  19792. this._markSubMeshesAsLightDirty();
  19793. };
  19794. /** @hidden */
  19795. AbstractMesh.prototype._resyncLighSource = function (light) {
  19796. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19797. var index = this._lightSources.indexOf(light);
  19798. if (index === -1) {
  19799. if (!isIn) {
  19800. return;
  19801. }
  19802. this._lightSources.push(light);
  19803. }
  19804. else {
  19805. if (isIn) {
  19806. return;
  19807. }
  19808. this._lightSources.splice(index, 1);
  19809. }
  19810. this._markSubMeshesAsLightDirty();
  19811. };
  19812. /** @hidden */
  19813. AbstractMesh.prototype._unBindEffect = function () {
  19814. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19815. var subMesh = _a[_i];
  19816. subMesh.setEffect(null);
  19817. }
  19818. };
  19819. /** @hidden */
  19820. AbstractMesh.prototype._removeLightSource = function (light) {
  19821. var index = this._lightSources.indexOf(light);
  19822. if (index === -1) {
  19823. return;
  19824. }
  19825. this._lightSources.splice(index, 1);
  19826. this._markSubMeshesAsLightDirty();
  19827. };
  19828. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19829. if (!this.subMeshes) {
  19830. return;
  19831. }
  19832. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19833. var subMesh = _a[_i];
  19834. if (subMesh._materialDefines) {
  19835. func(subMesh._materialDefines);
  19836. }
  19837. }
  19838. };
  19839. /** @hidden */
  19840. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19841. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19842. };
  19843. /** @hidden */
  19844. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19845. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19846. };
  19847. /** @hidden */
  19848. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19849. if (!this.subMeshes) {
  19850. return;
  19851. }
  19852. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19853. var subMesh = _a[_i];
  19854. var material = subMesh.getMaterial();
  19855. if (material) {
  19856. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19857. }
  19858. }
  19859. };
  19860. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19861. /**
  19862. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19863. */
  19864. get: function () {
  19865. return this._scaling;
  19866. },
  19867. set: function (newScaling) {
  19868. this._scaling = newScaling;
  19869. if (this.physicsImpostor) {
  19870. this.physicsImpostor.forceUpdate();
  19871. }
  19872. },
  19873. enumerable: true,
  19874. configurable: true
  19875. });
  19876. // Methods
  19877. /**
  19878. * Disables the mesh edge rendering mode
  19879. * @returns the currentAbstractMesh
  19880. */
  19881. AbstractMesh.prototype.disableEdgesRendering = function () {
  19882. if (this._edgesRenderer) {
  19883. this._edgesRenderer.dispose();
  19884. this._edgesRenderer = null;
  19885. }
  19886. return this;
  19887. };
  19888. /**
  19889. * Enables the edge rendering mode on the mesh.
  19890. * This mode makes the mesh edges visible
  19891. * @param epsilon defines the maximal distance between two angles to detect a face
  19892. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19893. * @returns the currentAbstractMesh
  19894. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19895. */
  19896. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19897. if (epsilon === void 0) { epsilon = 0.95; }
  19898. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19899. this.disableEdgesRendering();
  19900. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19901. return this;
  19902. };
  19903. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  19904. /**
  19905. * Gets the edgesRenderer associated with the mesh
  19906. */
  19907. get: function () {
  19908. return this._edgesRenderer;
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19914. /**
  19915. * Returns true if the mesh is blocked. Implemented by child classes
  19916. */
  19917. get: function () {
  19918. return false;
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. /**
  19924. * Returns the mesh itself by default. Implemented by child classes
  19925. * @param camera defines the camera to use to pick the right LOD level
  19926. * @returns the currentAbstractMesh
  19927. */
  19928. AbstractMesh.prototype.getLOD = function (camera) {
  19929. return this;
  19930. };
  19931. /**
  19932. * Returns 0 by default. Implemented by child classes
  19933. * @returns an integer
  19934. */
  19935. AbstractMesh.prototype.getTotalVertices = function () {
  19936. return 0;
  19937. };
  19938. /**
  19939. * Returns null by default. Implemented by child classes
  19940. * @returns null
  19941. */
  19942. AbstractMesh.prototype.getIndices = function () {
  19943. return null;
  19944. };
  19945. /**
  19946. * Returns the array of the requested vertex data kind. Implemented by child classes
  19947. * @param kind defines the vertex data kind to use
  19948. * @returns null
  19949. */
  19950. AbstractMesh.prototype.getVerticesData = function (kind) {
  19951. return null;
  19952. };
  19953. /**
  19954. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19955. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19956. * Note that a new underlying VertexBuffer object is created each call.
  19957. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19958. * @param kind defines vertex data kind:
  19959. * * BABYLON.VertexBuffer.PositionKind
  19960. * * BABYLON.VertexBuffer.UVKind
  19961. * * BABYLON.VertexBuffer.UV2Kind
  19962. * * BABYLON.VertexBuffer.UV3Kind
  19963. * * BABYLON.VertexBuffer.UV4Kind
  19964. * * BABYLON.VertexBuffer.UV5Kind
  19965. * * BABYLON.VertexBuffer.UV6Kind
  19966. * * BABYLON.VertexBuffer.ColorKind
  19967. * * BABYLON.VertexBuffer.MatricesIndicesKind
  19968. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19969. * * BABYLON.VertexBuffer.MatricesWeightsKind
  19970. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19971. * @param data defines the data source
  19972. * @param updatable defines if the data must be flagged as updatable (or static)
  19973. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  19974. * @returns the current mesh
  19975. */
  19976. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19977. return this;
  19978. };
  19979. /**
  19980. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19981. * If the mesh has no geometry, it is simply returned as it is.
  19982. * @param kind defines vertex data kind:
  19983. * * BABYLON.VertexBuffer.PositionKind
  19984. * * BABYLON.VertexBuffer.UVKind
  19985. * * BABYLON.VertexBuffer.UV2Kind
  19986. * * BABYLON.VertexBuffer.UV3Kind
  19987. * * BABYLON.VertexBuffer.UV4Kind
  19988. * * BABYLON.VertexBuffer.UV5Kind
  19989. * * BABYLON.VertexBuffer.UV6Kind
  19990. * * BABYLON.VertexBuffer.ColorKind
  19991. * * BABYLON.VertexBuffer.MatricesIndicesKind
  19992. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19993. * * BABYLON.VertexBuffer.MatricesWeightsKind
  19994. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19995. * @param data defines the data source
  19996. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  19997. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  19998. * @returns the current mesh
  19999. */
  20000. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20001. return this;
  20002. };
  20003. /**
  20004. * Sets the mesh indices,
  20005. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20006. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20007. * @param totalVertices Defines the total number of vertices
  20008. * @returns the current mesh
  20009. */
  20010. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20011. return this;
  20012. };
  20013. /**
  20014. * Gets a boolean indicating if specific vertex data is present
  20015. * @param kind defines the vertex data kind to use
  20016. * @returns true is data kind is present
  20017. */
  20018. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20019. return false;
  20020. };
  20021. /**
  20022. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20023. * @returns a BoundingInfo
  20024. */
  20025. AbstractMesh.prototype.getBoundingInfo = function () {
  20026. if (this._masterMesh) {
  20027. return this._masterMesh.getBoundingInfo();
  20028. }
  20029. if (!this._boundingInfo) {
  20030. // this._boundingInfo is being created here
  20031. this._updateBoundingInfo();
  20032. }
  20033. // cannot be null.
  20034. return this._boundingInfo;
  20035. };
  20036. /**
  20037. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20038. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20039. * @returns the current mesh
  20040. */
  20041. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20042. if (includeDescendants === void 0) { includeDescendants = true; }
  20043. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20044. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20045. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20046. if (maxDimension === 0) {
  20047. return this;
  20048. }
  20049. var scale = 1 / maxDimension;
  20050. this.scaling.scaleInPlace(scale);
  20051. return this;
  20052. };
  20053. /**
  20054. * Overwrite the current bounding info
  20055. * @param boundingInfo defines the new bounding info
  20056. * @returns the current mesh
  20057. */
  20058. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20059. this._boundingInfo = boundingInfo;
  20060. return this;
  20061. };
  20062. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20063. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20064. get: function () {
  20065. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20066. },
  20067. enumerable: true,
  20068. configurable: true
  20069. });
  20070. /** @hidden */
  20071. AbstractMesh.prototype._preActivate = function () {
  20072. };
  20073. /** @hidden */
  20074. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20075. };
  20076. /** @hidden */
  20077. AbstractMesh.prototype._activate = function (renderId) {
  20078. this._renderId = renderId;
  20079. };
  20080. /**
  20081. * Gets the current world matrix
  20082. * @returns a Matrix
  20083. */
  20084. AbstractMesh.prototype.getWorldMatrix = function () {
  20085. if (this._masterMesh) {
  20086. return this._masterMesh.getWorldMatrix();
  20087. }
  20088. return _super.prototype.getWorldMatrix.call(this);
  20089. };
  20090. /** @hidden */
  20091. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20092. if (this._masterMesh) {
  20093. return this._masterMesh._getWorldMatrixDeterminant();
  20094. }
  20095. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20096. };
  20097. // ================================== Point of View Movement =================================
  20098. /**
  20099. * Perform relative position change from the point of view of behind the front of the mesh.
  20100. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20101. * Supports definition of mesh facing forward or backward
  20102. * @param amountRight defines the distance on the right axis
  20103. * @param amountUp defines the distance on the up axis
  20104. * @param amountForward defines the distance on the forward axis
  20105. * @returns the current mesh
  20106. */
  20107. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20108. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20109. return this;
  20110. };
  20111. /**
  20112. * Calculate relative position change from the point of view of behind the front of the mesh.
  20113. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20114. * Supports definition of mesh facing forward or backward
  20115. * @param amountRight defines the distance on the right axis
  20116. * @param amountUp defines the distance on the up axis
  20117. * @param amountForward defines the distance on the forward axis
  20118. * @returns the new displacement vector
  20119. */
  20120. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20121. var rotMatrix = new BABYLON.Matrix();
  20122. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20123. rotQuaternion.toRotationMatrix(rotMatrix);
  20124. var translationDelta = BABYLON.Vector3.Zero();
  20125. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20126. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20127. return translationDelta;
  20128. };
  20129. // ================================== Point of View Rotation =================================
  20130. /**
  20131. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20132. * Supports definition of mesh facing forward or backward
  20133. * @param flipBack defines the flip
  20134. * @param twirlClockwise defines the twirl
  20135. * @param tiltRight defines the tilt
  20136. * @returns the current mesh
  20137. */
  20138. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20139. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20140. return this;
  20141. };
  20142. /**
  20143. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20144. * Supports definition of mesh facing forward or backward.
  20145. * @param flipBack defines the flip
  20146. * @param twirlClockwise defines the twirl
  20147. * @param tiltRight defines the tilt
  20148. * @returns the new rotation vector
  20149. */
  20150. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20151. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20152. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20153. };
  20154. /**
  20155. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20156. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20157. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20158. * @returns the new bounding vectors
  20159. */
  20160. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20161. if (includeDescendants === void 0) { includeDescendants = true; }
  20162. if (predicate === void 0) { predicate = null; }
  20163. // Ensures that all world matrix will be recomputed.
  20164. this.getScene().incrementRenderId();
  20165. this.computeWorldMatrix(true);
  20166. var min;
  20167. var max;
  20168. var boundingInfo = this.getBoundingInfo();
  20169. if (!this.subMeshes) {
  20170. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20171. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20172. }
  20173. else {
  20174. min = boundingInfo.boundingBox.minimumWorld;
  20175. max = boundingInfo.boundingBox.maximumWorld;
  20176. }
  20177. if (includeDescendants) {
  20178. var descendants = this.getDescendants(false);
  20179. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20180. var descendant = descendants_1[_i];
  20181. var childMesh = descendant;
  20182. childMesh.computeWorldMatrix(true);
  20183. // Filters meshes based on custom predicate function.
  20184. if (predicate && !predicate(childMesh)) {
  20185. continue;
  20186. }
  20187. //make sure we have the needed params to get mix and max
  20188. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20189. continue;
  20190. }
  20191. var childBoundingInfo = childMesh.getBoundingInfo();
  20192. var boundingBox = childBoundingInfo.boundingBox;
  20193. var minBox = boundingBox.minimumWorld;
  20194. var maxBox = boundingBox.maximumWorld;
  20195. BABYLON.Tools.CheckExtends(minBox, min, max);
  20196. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20197. }
  20198. }
  20199. return {
  20200. min: min,
  20201. max: max
  20202. };
  20203. };
  20204. /** @hidden */
  20205. AbstractMesh.prototype._updateBoundingInfo = function () {
  20206. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20207. this._boundingInfo.update(this.worldMatrixFromCache);
  20208. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20209. return this;
  20210. };
  20211. /** @hidden */
  20212. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20213. if (!this.subMeshes) {
  20214. return this;
  20215. }
  20216. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20217. var subMesh = this.subMeshes[subIndex];
  20218. if (!subMesh.IsGlobal) {
  20219. subMesh.updateBoundingInfo(matrix);
  20220. }
  20221. }
  20222. return this;
  20223. };
  20224. /** @hidden */
  20225. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20226. // Bounding info
  20227. this._updateBoundingInfo();
  20228. };
  20229. /**
  20230. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20231. * A mesh is in the frustum if its bounding box intersects the frustum
  20232. * @param frustumPlanes defines the frustum to test
  20233. * @returns true if the mesh is in the frustum planes
  20234. */
  20235. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20236. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20237. };
  20238. /**
  20239. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20240. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20241. * @param frustumPlanes defines the frustum to test
  20242. * @returns true if the mesh is completely in the frustum planes
  20243. */
  20244. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20245. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20246. };
  20247. /**
  20248. * True if the mesh intersects another mesh or a SolidParticle object
  20249. * @param mesh defines a target mesh or SolidParticle to test
  20250. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20251. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20252. * @returns true if there is an intersection
  20253. */
  20254. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20255. if (precise === void 0) { precise = false; }
  20256. if (!this._boundingInfo || !mesh._boundingInfo) {
  20257. return false;
  20258. }
  20259. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20260. return true;
  20261. }
  20262. if (includeDescendants) {
  20263. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20264. var child = _a[_i];
  20265. if (child.intersectsMesh(mesh, precise, true)) {
  20266. return true;
  20267. }
  20268. }
  20269. }
  20270. return false;
  20271. };
  20272. /**
  20273. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20274. * @param point defines the point to test
  20275. * @returns true if there is an intersection
  20276. */
  20277. AbstractMesh.prototype.intersectsPoint = function (point) {
  20278. if (!this._boundingInfo) {
  20279. return false;
  20280. }
  20281. return this._boundingInfo.intersectsPoint(point);
  20282. };
  20283. /**
  20284. * Gets the current physics impostor
  20285. * @see http://doc.babylonjs.com/features/physics_engine
  20286. * @returns a physics impostor or null
  20287. */
  20288. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20289. return this.physicsImpostor;
  20290. };
  20291. /**
  20292. * Gets the position of the current mesh in camera space
  20293. * @param camera defines the camera to use
  20294. * @returns a position
  20295. */
  20296. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20297. if (camera === void 0) { camera = null; }
  20298. if (!camera) {
  20299. camera = this.getScene().activeCamera;
  20300. }
  20301. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20302. };
  20303. /**
  20304. * Returns the distance from the mesh to the active camera
  20305. * @param camera defines the camera to use
  20306. * @returns the distance
  20307. */
  20308. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20309. if (camera === void 0) { camera = null; }
  20310. if (!camera) {
  20311. camera = this.getScene().activeCamera;
  20312. }
  20313. return this.absolutePosition.subtract(camera.position).length();
  20314. };
  20315. /**
  20316. * Apply a physic impulse to the mesh
  20317. * @param force defines the force to apply
  20318. * @param contactPoint defines where to apply the force
  20319. * @returns the current mesh
  20320. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20321. */
  20322. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20323. if (!this.physicsImpostor) {
  20324. return this;
  20325. }
  20326. this.physicsImpostor.applyImpulse(force, contactPoint);
  20327. return this;
  20328. };
  20329. /**
  20330. * Creates a physic joint between two meshes
  20331. * @param otherMesh defines the other mesh to use
  20332. * @param pivot1 defines the pivot to use on this mesh
  20333. * @param pivot2 defines the pivot to use on the other mesh
  20334. * @param options defines additional options (can be plugin dependent)
  20335. * @returns the current mesh
  20336. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20337. */
  20338. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20339. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20340. return this;
  20341. }
  20342. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20343. mainPivot: pivot1,
  20344. connectedPivot: pivot2,
  20345. nativeParams: options
  20346. });
  20347. return this;
  20348. };
  20349. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20350. // Collisions
  20351. /**
  20352. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20353. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20354. */
  20355. get: function () {
  20356. return this._checkCollisions;
  20357. },
  20358. set: function (collisionEnabled) {
  20359. this._checkCollisions = collisionEnabled;
  20360. if (this.getScene().workerCollisions) {
  20361. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20362. }
  20363. },
  20364. enumerable: true,
  20365. configurable: true
  20366. });
  20367. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20368. /**
  20369. * Gets Collider object used to compute collisions (not physics)
  20370. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20371. */
  20372. get: function () {
  20373. return this._collider;
  20374. },
  20375. enumerable: true,
  20376. configurable: true
  20377. });
  20378. /**
  20379. * Move the mesh using collision engine
  20380. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20381. * @param displacement defines the requested displacement vector
  20382. * @returns the current mesh
  20383. */
  20384. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20385. var globalPosition = this.getAbsolutePosition();
  20386. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20387. if (!this._collider) {
  20388. this._collider = new BABYLON.Collider();
  20389. }
  20390. this._collider._radius = this.ellipsoid;
  20391. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20392. return this;
  20393. };
  20394. // Submeshes octree
  20395. /**
  20396. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20397. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20398. * @param maxCapacity defines the maximum size of each block (64 by default)
  20399. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20400. * @returns the new octree
  20401. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20402. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20403. */
  20404. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20405. if (maxCapacity === void 0) { maxCapacity = 64; }
  20406. if (maxDepth === void 0) { maxDepth = 2; }
  20407. if (!this._submeshesOctree) {
  20408. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20409. }
  20410. this.computeWorldMatrix(true);
  20411. var boundingInfo = this.getBoundingInfo();
  20412. // Update octree
  20413. var bbox = boundingInfo.boundingBox;
  20414. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20415. return this._submeshesOctree;
  20416. };
  20417. // Collisions
  20418. /** @hidden */
  20419. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20420. this._generatePointsArray();
  20421. if (!this._positions) {
  20422. return this;
  20423. }
  20424. // Transformation
  20425. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20426. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20427. subMesh._lastColliderWorldVertices = [];
  20428. subMesh._trianglePlanes = [];
  20429. var start = subMesh.verticesStart;
  20430. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20431. for (var i = start; i < end; i++) {
  20432. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20433. }
  20434. }
  20435. // Collide
  20436. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20437. if (collider.collisionFound) {
  20438. collider.collidedMesh = this;
  20439. }
  20440. return this;
  20441. };
  20442. /** @hidden */
  20443. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20444. var subMeshes;
  20445. var len;
  20446. // Octrees
  20447. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20448. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20449. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20450. len = intersections.length;
  20451. subMeshes = intersections.data;
  20452. }
  20453. else {
  20454. subMeshes = this.subMeshes;
  20455. len = subMeshes.length;
  20456. }
  20457. for (var index = 0; index < len; index++) {
  20458. var subMesh = subMeshes[index];
  20459. // Bounding test
  20460. if (len > 1 && !subMesh._checkCollision(collider))
  20461. continue;
  20462. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20463. }
  20464. return this;
  20465. };
  20466. /** @hidden */
  20467. AbstractMesh.prototype._checkCollision = function (collider) {
  20468. // Bounding box test
  20469. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20470. return this;
  20471. // Transformation matrix
  20472. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20473. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20474. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20475. return this;
  20476. };
  20477. // Picking
  20478. /** @hidden */
  20479. AbstractMesh.prototype._generatePointsArray = function () {
  20480. return false;
  20481. };
  20482. /**
  20483. * Checks if the passed Ray intersects with the mesh
  20484. * @param ray defines the ray to use
  20485. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20486. * @returns the picking info
  20487. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20488. */
  20489. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20490. var pickingInfo = new BABYLON.PickingInfo();
  20491. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20492. return pickingInfo;
  20493. }
  20494. if (!this._generatePointsArray()) {
  20495. return pickingInfo;
  20496. }
  20497. var intersectInfo = null;
  20498. // Octrees
  20499. var subMeshes;
  20500. var len;
  20501. if (this._submeshesOctree && this.useOctreeForPicking) {
  20502. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20503. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20504. len = intersections.length;
  20505. subMeshes = intersections.data;
  20506. }
  20507. else {
  20508. subMeshes = this.subMeshes;
  20509. len = subMeshes.length;
  20510. }
  20511. for (var index = 0; index < len; index++) {
  20512. var subMesh = subMeshes[index];
  20513. // Bounding test
  20514. if (len > 1 && !subMesh.canIntersects(ray))
  20515. continue;
  20516. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20517. if (currentIntersectInfo) {
  20518. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20519. intersectInfo = currentIntersectInfo;
  20520. intersectInfo.subMeshId = index;
  20521. if (fastCheck) {
  20522. break;
  20523. }
  20524. }
  20525. }
  20526. }
  20527. if (intersectInfo) {
  20528. // Get picked point
  20529. var world = this.getWorldMatrix();
  20530. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20531. var direction = ray.direction.clone();
  20532. direction = direction.scale(intersectInfo.distance);
  20533. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20534. var pickedPoint = worldOrigin.add(worldDirection);
  20535. // Return result
  20536. pickingInfo.hit = true;
  20537. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20538. pickingInfo.pickedPoint = pickedPoint;
  20539. pickingInfo.pickedMesh = this;
  20540. pickingInfo.bu = intersectInfo.bu || 0;
  20541. pickingInfo.bv = intersectInfo.bv || 0;
  20542. pickingInfo.faceId = intersectInfo.faceId;
  20543. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20544. return pickingInfo;
  20545. }
  20546. return pickingInfo;
  20547. };
  20548. /**
  20549. * Clones the current mesh
  20550. * @param name defines the mesh name
  20551. * @param newParent defines the new mesh parent
  20552. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20553. * @returns the new mesh
  20554. */
  20555. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20556. return null;
  20557. };
  20558. /**
  20559. * Disposes all the submeshes of the current meshnp
  20560. * @returns the current mesh
  20561. */
  20562. AbstractMesh.prototype.releaseSubMeshes = function () {
  20563. if (this.subMeshes) {
  20564. while (this.subMeshes.length) {
  20565. this.subMeshes[0].dispose();
  20566. }
  20567. }
  20568. else {
  20569. this.subMeshes = new Array();
  20570. }
  20571. return this;
  20572. };
  20573. /**
  20574. * Releases resources associated with this abstract mesh.
  20575. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20576. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20577. */
  20578. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20579. var _this = this;
  20580. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20581. var index;
  20582. // Smart Array Retainers.
  20583. this.getScene().freeActiveMeshes();
  20584. this.getScene().freeRenderingGroups();
  20585. // Action manager
  20586. if (this.actionManager !== undefined && this.actionManager !== null) {
  20587. this.actionManager.dispose();
  20588. this.actionManager = null;
  20589. }
  20590. // Skeleton
  20591. this._skeleton = null;
  20592. // Physics
  20593. if (this.physicsImpostor) {
  20594. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20595. }
  20596. // Intersections in progress
  20597. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20598. var other = this._intersectionsInProgress[index];
  20599. var pos = other._intersectionsInProgress.indexOf(this);
  20600. other._intersectionsInProgress.splice(pos, 1);
  20601. }
  20602. this._intersectionsInProgress = [];
  20603. // Lights
  20604. var lights = this.getScene().lights;
  20605. lights.forEach(function (light) {
  20606. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20607. if (meshIndex !== -1) {
  20608. light.includedOnlyMeshes.splice(meshIndex, 1);
  20609. }
  20610. meshIndex = light.excludedMeshes.indexOf(_this);
  20611. if (meshIndex !== -1) {
  20612. light.excludedMeshes.splice(meshIndex, 1);
  20613. }
  20614. // Shadow generators
  20615. var generator = light.getShadowGenerator();
  20616. if (generator) {
  20617. var shadowMap = generator.getShadowMap();
  20618. if (shadowMap && shadowMap.renderList) {
  20619. meshIndex = shadowMap.renderList.indexOf(_this);
  20620. if (meshIndex !== -1) {
  20621. shadowMap.renderList.splice(meshIndex, 1);
  20622. }
  20623. }
  20624. }
  20625. });
  20626. // Edges
  20627. if (this._edgesRenderer) {
  20628. this._edgesRenderer.dispose();
  20629. this._edgesRenderer = null;
  20630. }
  20631. // SubMeshes
  20632. if (this.getClassName() !== "InstancedMesh") {
  20633. this.releaseSubMeshes();
  20634. }
  20635. // Octree
  20636. var sceneOctree = this.getScene().selectionOctree;
  20637. if (sceneOctree !== undefined && sceneOctree !== null) {
  20638. var index = sceneOctree.dynamicContent.indexOf(this);
  20639. if (index !== -1) {
  20640. sceneOctree.dynamicContent.splice(index, 1);
  20641. }
  20642. }
  20643. // Query
  20644. var engine = this.getScene().getEngine();
  20645. if (this._occlusionQuery) {
  20646. this._isOcclusionQueryInProgress = false;
  20647. engine.deleteQuery(this._occlusionQuery);
  20648. this._occlusionQuery = null;
  20649. }
  20650. // Engine
  20651. engine.wipeCaches();
  20652. // Remove from scene
  20653. this.getScene().removeMesh(this);
  20654. if (disposeMaterialAndTextures) {
  20655. if (this.material) {
  20656. this.material.dispose(false, true);
  20657. }
  20658. }
  20659. if (!doNotRecurse) {
  20660. // Particles
  20661. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20662. if (this.getScene().particleSystems[index].emitter === this) {
  20663. this.getScene().particleSystems[index].dispose();
  20664. index--;
  20665. }
  20666. }
  20667. }
  20668. // facet data
  20669. if (this._facetDataEnabled) {
  20670. this.disableFacetData();
  20671. }
  20672. this.onAfterWorldMatrixUpdateObservable.clear();
  20673. this.onCollideObservable.clear();
  20674. this.onCollisionPositionChangeObservable.clear();
  20675. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20676. };
  20677. /**
  20678. * Adds the passed mesh as a child to the current mesh
  20679. * @param mesh defines the child mesh
  20680. * @returns the current mesh
  20681. */
  20682. AbstractMesh.prototype.addChild = function (mesh) {
  20683. mesh.setParent(this);
  20684. return this;
  20685. };
  20686. /**
  20687. * Removes the passed mesh from the current mesh children list
  20688. * @param mesh defines the child mesh
  20689. * @returns the current mesh
  20690. */
  20691. AbstractMesh.prototype.removeChild = function (mesh) {
  20692. mesh.setParent(null);
  20693. return this;
  20694. };
  20695. // Facet data
  20696. /** @hidden */
  20697. AbstractMesh.prototype._initFacetData = function () {
  20698. if (!this._facetNormals) {
  20699. this._facetNormals = new Array();
  20700. }
  20701. if (!this._facetPositions) {
  20702. this._facetPositions = new Array();
  20703. }
  20704. if (!this._facetPartitioning) {
  20705. this._facetPartitioning = new Array();
  20706. }
  20707. this._facetNb = (this.getIndices().length / 3) | 0;
  20708. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20709. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20710. for (var f = 0; f < this._facetNb; f++) {
  20711. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20712. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20713. }
  20714. this._facetDataEnabled = true;
  20715. return this;
  20716. };
  20717. /**
  20718. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20719. * This method can be called within the render loop.
  20720. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation
  20721. * @returns the current mesh
  20722. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20723. */
  20724. AbstractMesh.prototype.updateFacetData = function () {
  20725. if (!this._facetDataEnabled) {
  20726. this._initFacetData();
  20727. }
  20728. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20729. var indices = this.getIndices();
  20730. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20731. var bInfo = this.getBoundingInfo();
  20732. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20733. // init arrays, matrix and sort function on first call
  20734. this._facetDepthSortEnabled = true;
  20735. if (indices instanceof Uint16Array) {
  20736. this._depthSortedIndices = new Uint16Array(indices);
  20737. }
  20738. else if (indices instanceof Uint32Array) {
  20739. this._depthSortedIndices = new Uint32Array(indices);
  20740. }
  20741. else {
  20742. var needs32bits = false;
  20743. for (var i = 0; i < indices.length; i++) {
  20744. if (indices[i] > 65535) {
  20745. needs32bits = true;
  20746. break;
  20747. }
  20748. }
  20749. if (needs32bits) {
  20750. this._depthSortedIndices = new Uint32Array(indices);
  20751. }
  20752. else {
  20753. this._depthSortedIndices = new Uint16Array(indices);
  20754. }
  20755. }
  20756. this._facetDepthSortFunction = function (f1, f2) {
  20757. return (f2.sqDistance - f1.sqDistance);
  20758. };
  20759. if (!this._facetDepthSortFrom) {
  20760. var camera = this.getScene().activeCamera;
  20761. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20762. }
  20763. this._depthSortedFacets = [];
  20764. for (var f = 0; f < this._facetNb; f++) {
  20765. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20766. this._depthSortedFacets.push(depthSortedFacet);
  20767. }
  20768. this._invertedMatrix = BABYLON.Matrix.Identity();
  20769. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20770. }
  20771. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20772. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20773. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20774. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20775. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20776. this._subDiv.max = this._partitioningSubdivisions;
  20777. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20778. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20779. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20780. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20781. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20782. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20783. // set the parameters for ComputeNormals()
  20784. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20785. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20786. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20787. this._facetParameters.bInfo = bInfo;
  20788. this._facetParameters.bbSize = this._bbSize;
  20789. this._facetParameters.subDiv = this._subDiv;
  20790. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20791. this._facetParameters.depthSort = this._facetDepthSort;
  20792. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20793. this.computeWorldMatrix(true);
  20794. this._worldMatrix.invertToRef(this._invertedMatrix);
  20795. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20796. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20797. }
  20798. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20799. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20800. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20801. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20802. var l = (this._depthSortedIndices.length / 3) | 0;
  20803. for (var f = 0; f < l; f++) {
  20804. var sind = this._depthSortedFacets[f].ind;
  20805. this._depthSortedIndices[f * 3] = indices[sind];
  20806. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20807. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20808. }
  20809. this.updateIndices(this._depthSortedIndices);
  20810. }
  20811. return this;
  20812. };
  20813. /**
  20814. * Returns the facetLocalNormals array.
  20815. * The normals are expressed in the mesh local spac
  20816. * @returns an array of Vector3
  20817. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20818. */
  20819. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20820. if (!this._facetNormals) {
  20821. this.updateFacetData();
  20822. }
  20823. return this._facetNormals;
  20824. };
  20825. /**
  20826. * Returns the facetLocalPositions array.
  20827. * The facet positions are expressed in the mesh local space
  20828. * @returns an array of Vector3
  20829. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20830. */
  20831. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20832. if (!this._facetPositions) {
  20833. this.updateFacetData();
  20834. }
  20835. return this._facetPositions;
  20836. };
  20837. /**
  20838. * Returns the facetLocalPartioning array
  20839. * @returns an array of array of numbers
  20840. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20841. */
  20842. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20843. if (!this._facetPartitioning) {
  20844. this.updateFacetData();
  20845. }
  20846. return this._facetPartitioning;
  20847. };
  20848. /**
  20849. * Returns the i-th facet position in the world system.
  20850. * This method allocates a new Vector3 per call
  20851. * @param i defines the facet index
  20852. * @returns a new Vector3
  20853. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20854. */
  20855. AbstractMesh.prototype.getFacetPosition = function (i) {
  20856. var pos = BABYLON.Vector3.Zero();
  20857. this.getFacetPositionToRef(i, pos);
  20858. return pos;
  20859. };
  20860. /**
  20861. * Sets the reference Vector3 with the i-th facet position in the world system
  20862. * @param i defines the facet index
  20863. * @param ref defines the target vector
  20864. * @returns the current mesh
  20865. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20866. */
  20867. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20868. var localPos = (this.getFacetLocalPositions())[i];
  20869. var world = this.getWorldMatrix();
  20870. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20871. return this;
  20872. };
  20873. /**
  20874. * Returns the i-th facet normal in the world system.
  20875. * This method allocates a new Vector3 per call
  20876. * @param i defines the facet index
  20877. * @returns a new Vector3
  20878. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20879. */
  20880. AbstractMesh.prototype.getFacetNormal = function (i) {
  20881. var norm = BABYLON.Vector3.Zero();
  20882. this.getFacetNormalToRef(i, norm);
  20883. return norm;
  20884. };
  20885. /**
  20886. * Sets the reference Vector3 with the i-th facet normal in the world system
  20887. * @param i defines the facet index
  20888. * @param ref defines the target vector
  20889. * @returns the current mesh
  20890. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20891. */
  20892. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20893. var localNorm = (this.getFacetLocalNormals())[i];
  20894. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20895. return this;
  20896. };
  20897. /**
  20898. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)
  20899. * @param x defines x coordinate
  20900. * @param y defines y coordinate
  20901. * @param z defines z coordinate
  20902. * @returns the array of facet indexes
  20903. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20904. */
  20905. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20906. var bInfo = this.getBoundingInfo();
  20907. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20908. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20909. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20910. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20911. return null;
  20912. }
  20913. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20914. };
  20915. /**
  20916. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20917. * @param projected sets as the (x,y,z) world projection on the facet
  20918. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  20919. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  20920. * @param x defines x coordinate
  20921. * @param y defines y coordinate
  20922. * @param z defines z coordinate
  20923. * @returns the face index if found (or null instead)
  20924. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20925. */
  20926. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20927. if (checkFace === void 0) { checkFace = false; }
  20928. if (facing === void 0) { facing = true; }
  20929. var world = this.getWorldMatrix();
  20930. var invMat = BABYLON.Tmp.Matrix[5];
  20931. world.invertToRef(invMat);
  20932. var invVect = BABYLON.Tmp.Vector3[8];
  20933. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20934. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20935. if (projected) {
  20936. // tranform the local computed projected vector to world coordinates
  20937. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20938. }
  20939. return closest;
  20940. };
  20941. /**
  20942. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  20943. * @param projected sets as the (x,y,z) local projection on the facet
  20944. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  20945. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  20946. * @param x defines x coordinate
  20947. * @param y defines y coordinate
  20948. * @param z defines z coordinate
  20949. * @returns the face index if found (or null instead)
  20950. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20951. */
  20952. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20953. if (checkFace === void 0) { checkFace = false; }
  20954. if (facing === void 0) { facing = true; }
  20955. var closest = null;
  20956. var tmpx = 0.0;
  20957. var tmpy = 0.0;
  20958. var tmpz = 0.0;
  20959. var d = 0.0; // tmp dot facet normal * facet position
  20960. var t0 = 0.0;
  20961. var projx = 0.0;
  20962. var projy = 0.0;
  20963. var projz = 0.0;
  20964. // Get all the facets in the same partitioning block than (x, y, z)
  20965. var facetPositions = this.getFacetLocalPositions();
  20966. var facetNormals = this.getFacetLocalNormals();
  20967. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20968. if (!facetsInBlock) {
  20969. return null;
  20970. }
  20971. // Get the closest facet to (x, y, z)
  20972. var shortest = Number.MAX_VALUE; // init distance vars
  20973. var tmpDistance = shortest;
  20974. var fib; // current facet in the block
  20975. var norm; // current facet normal
  20976. var p0; // current facet barycenter position
  20977. // loop on all the facets in the current partitioning block
  20978. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20979. fib = facetsInBlock[idx];
  20980. norm = facetNormals[fib];
  20981. p0 = facetPositions[fib];
  20982. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20983. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20984. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20985. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20986. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20987. projx = x + norm.x * t0;
  20988. projy = y + norm.y * t0;
  20989. projz = z + norm.z * t0;
  20990. tmpx = projx - x;
  20991. tmpy = projy - y;
  20992. tmpz = projz - z;
  20993. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20994. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  20995. shortest = tmpDistance;
  20996. closest = fib;
  20997. if (projected) {
  20998. projected.x = projx;
  20999. projected.y = projy;
  21000. projected.z = projz;
  21001. }
  21002. }
  21003. }
  21004. }
  21005. return closest;
  21006. };
  21007. /**
  21008. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21009. * @returns the parameters
  21010. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21011. */
  21012. AbstractMesh.prototype.getFacetDataParameters = function () {
  21013. return this._facetParameters;
  21014. };
  21015. /**
  21016. * Disables the feature FacetData and frees the related memory
  21017. * @returns the current mesh
  21018. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21019. */
  21020. AbstractMesh.prototype.disableFacetData = function () {
  21021. if (this._facetDataEnabled) {
  21022. this._facetDataEnabled = false;
  21023. this._facetPositions = new Array();
  21024. this._facetNormals = new Array();
  21025. this._facetPartitioning = new Array();
  21026. this._facetParameters = null;
  21027. this._depthSortedIndices = new Uint32Array(0);
  21028. }
  21029. return this;
  21030. };
  21031. /**
  21032. * Updates the AbstractMesh indices array
  21033. * @param indices defines the data source
  21034. * @returns the current mesh
  21035. */
  21036. AbstractMesh.prototype.updateIndices = function (indices) {
  21037. return this;
  21038. };
  21039. /**
  21040. * Creates new normals data for the mesh
  21041. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21042. * @returns the current mesh
  21043. */
  21044. AbstractMesh.prototype.createNormals = function (updatable) {
  21045. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21046. var indices = this.getIndices();
  21047. var normals;
  21048. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21049. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21050. }
  21051. else {
  21052. normals = [];
  21053. }
  21054. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21055. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21056. return this;
  21057. };
  21058. /**
  21059. * Align the mesh with a normal
  21060. * @param normal defines the normal to use
  21061. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21062. * @returns the current mesh
  21063. */
  21064. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21065. if (!upDirection) {
  21066. upDirection = BABYLON.Axis.Y;
  21067. }
  21068. var axisX = BABYLON.Tmp.Vector3[0];
  21069. var axisZ = BABYLON.Tmp.Vector3[1];
  21070. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21071. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21072. if (this.rotationQuaternion) {
  21073. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21074. }
  21075. else {
  21076. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21077. }
  21078. return this;
  21079. };
  21080. /** @hidden */
  21081. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21082. this._isOccluded = false;
  21083. };
  21084. /** No occlusion */
  21085. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21086. /** Occlusion set to optimisitic */
  21087. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21088. /** Occlusion set to strict */
  21089. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21090. /** Use an accurante occlusion algorithm */
  21091. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21092. /** Use a conservative occlusion algorithm */
  21093. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21094. return AbstractMesh;
  21095. }(BABYLON.TransformNode));
  21096. BABYLON.AbstractMesh = AbstractMesh;
  21097. })(BABYLON || (BABYLON = {}));
  21098. //# sourceMappingURL=babylon.abstractMesh.js.map
  21099. var BABYLON;
  21100. (function (BABYLON) {
  21101. /**
  21102. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21103. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21104. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  21105. */
  21106. var Light = /** @class */ (function (_super) {
  21107. __extends(Light, _super);
  21108. /**
  21109. * Creates a Light object in the scene.
  21110. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21111. * @param name The firendly name of the light
  21112. * @param scene The scene the light belongs too
  21113. */
  21114. function Light(name, scene) {
  21115. var _this = _super.call(this, name, scene) || this;
  21116. /**
  21117. * Diffuse gives the basic color to an object.
  21118. */
  21119. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21120. /**
  21121. * Specular produces a highlight color on an object.
  21122. * Note: This is note affecting PBR materials.
  21123. */
  21124. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21125. /**
  21126. * Strength of the light.
  21127. * Note: By default it is define in the framework own unit.
  21128. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21129. */
  21130. _this.intensity = 1.0;
  21131. /**
  21132. * Defines how far from the source the light is impacting in scene units.
  21133. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21134. */
  21135. _this.range = Number.MAX_VALUE;
  21136. /**
  21137. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21138. * of light.
  21139. */
  21140. _this._photometricScale = 1.0;
  21141. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21142. _this._radius = 0.00001;
  21143. /**
  21144. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21145. * exceeding the number allowed of the materials.
  21146. */
  21147. _this.renderPriority = 0;
  21148. _this._shadowEnabled = true;
  21149. _this._excludeWithLayerMask = 0;
  21150. _this._includeOnlyWithLayerMask = 0;
  21151. _this._lightmapMode = 0;
  21152. /**
  21153. * @hidden Internal use only.
  21154. */
  21155. _this._excludedMeshesIds = new Array();
  21156. /**
  21157. * @hidden Internal use only.
  21158. */
  21159. _this._includedOnlyMeshesIds = new Array();
  21160. _this.getScene().addLight(_this);
  21161. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21162. _this._buildUniformLayout();
  21163. _this.includedOnlyMeshes = new Array();
  21164. _this.excludedMeshes = new Array();
  21165. _this._resyncMeshes();
  21166. return _this;
  21167. }
  21168. Object.defineProperty(Light.prototype, "intensityMode", {
  21169. /**
  21170. * Gets the photometric scale used to interpret the intensity.
  21171. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21172. */
  21173. get: function () {
  21174. return this._intensityMode;
  21175. },
  21176. /**
  21177. * Sets the photometric scale used to interpret the intensity.
  21178. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21179. */
  21180. set: function (value) {
  21181. this._intensityMode = value;
  21182. this._computePhotometricScale();
  21183. },
  21184. enumerable: true,
  21185. configurable: true
  21186. });
  21187. ;
  21188. ;
  21189. Object.defineProperty(Light.prototype, "radius", {
  21190. /**
  21191. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21192. */
  21193. get: function () {
  21194. return this._radius;
  21195. },
  21196. /**
  21197. * sets the light radius used by PBR Materials to simulate soft area lights.
  21198. */
  21199. set: function (value) {
  21200. this._radius = value;
  21201. this._computePhotometricScale();
  21202. },
  21203. enumerable: true,
  21204. configurable: true
  21205. });
  21206. ;
  21207. ;
  21208. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21209. /**
  21210. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21211. * the current shadow generator.
  21212. */
  21213. get: function () {
  21214. return this._shadowEnabled;
  21215. },
  21216. /**
  21217. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21218. * the current shadow generator.
  21219. */
  21220. set: function (value) {
  21221. if (this._shadowEnabled === value) {
  21222. return;
  21223. }
  21224. this._shadowEnabled = value;
  21225. this._markMeshesAsLightDirty();
  21226. },
  21227. enumerable: true,
  21228. configurable: true
  21229. });
  21230. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21231. /**
  21232. * Gets the only meshes impacted by this light.
  21233. */
  21234. get: function () {
  21235. return this._includedOnlyMeshes;
  21236. },
  21237. /**
  21238. * Sets the only meshes impacted by this light.
  21239. */
  21240. set: function (value) {
  21241. this._includedOnlyMeshes = value;
  21242. this._hookArrayForIncludedOnly(value);
  21243. },
  21244. enumerable: true,
  21245. configurable: true
  21246. });
  21247. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21248. /**
  21249. * Gets the meshes not impacted by this light.
  21250. */
  21251. get: function () {
  21252. return this._excludedMeshes;
  21253. },
  21254. /**
  21255. * Sets the meshes not impacted by this light.
  21256. */
  21257. set: function (value) {
  21258. this._excludedMeshes = value;
  21259. this._hookArrayForExcluded(value);
  21260. },
  21261. enumerable: true,
  21262. configurable: true
  21263. });
  21264. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21265. /**
  21266. * Gets the layer id use to find what meshes are not impacted by the light.
  21267. * Inactive if 0
  21268. */
  21269. get: function () {
  21270. return this._excludeWithLayerMask;
  21271. },
  21272. /**
  21273. * Sets the layer id use to find what meshes are not impacted by the light.
  21274. * Inactive if 0
  21275. */
  21276. set: function (value) {
  21277. this._excludeWithLayerMask = value;
  21278. this._resyncMeshes();
  21279. },
  21280. enumerable: true,
  21281. configurable: true
  21282. });
  21283. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21284. /**
  21285. * Gets the layer id use to find what meshes are impacted by the light.
  21286. * Inactive if 0
  21287. */
  21288. get: function () {
  21289. return this._includeOnlyWithLayerMask;
  21290. },
  21291. /**
  21292. * Sets the layer id use to find what meshes are impacted by the light.
  21293. * Inactive if 0
  21294. */
  21295. set: function (value) {
  21296. this._includeOnlyWithLayerMask = value;
  21297. this._resyncMeshes();
  21298. },
  21299. enumerable: true,
  21300. configurable: true
  21301. });
  21302. Object.defineProperty(Light.prototype, "lightmapMode", {
  21303. /**
  21304. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21305. */
  21306. get: function () {
  21307. return this._lightmapMode;
  21308. },
  21309. /**
  21310. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21311. */
  21312. set: function (value) {
  21313. if (this._lightmapMode === value) {
  21314. return;
  21315. }
  21316. this._lightmapMode = value;
  21317. this._markMeshesAsLightDirty();
  21318. },
  21319. enumerable: true,
  21320. configurable: true
  21321. });
  21322. /**
  21323. * Returns the string "Light".
  21324. * @returns the class name
  21325. */
  21326. Light.prototype.getClassName = function () {
  21327. return "Light";
  21328. };
  21329. /**
  21330. * Converts the light information to a readable string for debug purpose.
  21331. * @param fullDetails Supports for multiple levels of logging within scene loading
  21332. * @returns the human readable light info
  21333. */
  21334. Light.prototype.toString = function (fullDetails) {
  21335. var ret = "Name: " + this.name;
  21336. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21337. if (this.animations) {
  21338. for (var i = 0; i < this.animations.length; i++) {
  21339. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21340. }
  21341. }
  21342. if (fullDetails) {
  21343. }
  21344. return ret;
  21345. };
  21346. /**
  21347. * Set the enabled state of this node.
  21348. * @param value - the new enabled state
  21349. */
  21350. Light.prototype.setEnabled = function (value) {
  21351. _super.prototype.setEnabled.call(this, value);
  21352. this._resyncMeshes();
  21353. };
  21354. /**
  21355. * Returns the Light associated shadow generator if any.
  21356. * @return the associated shadow generator.
  21357. */
  21358. Light.prototype.getShadowGenerator = function () {
  21359. return this._shadowGenerator;
  21360. };
  21361. /**
  21362. * Returns a Vector3, the absolute light position in the World.
  21363. * @returns the world space position of the light
  21364. */
  21365. Light.prototype.getAbsolutePosition = function () {
  21366. return BABYLON.Vector3.Zero();
  21367. };
  21368. /**
  21369. * Specifies if the light will affect the passed mesh.
  21370. * @param mesh The mesh to test against the light
  21371. * @return true the mesh is affected otherwise, false.
  21372. */
  21373. Light.prototype.canAffectMesh = function (mesh) {
  21374. if (!mesh) {
  21375. return true;
  21376. }
  21377. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21378. return false;
  21379. }
  21380. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21381. return false;
  21382. }
  21383. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21384. return false;
  21385. }
  21386. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21387. return false;
  21388. }
  21389. return true;
  21390. };
  21391. /**
  21392. * Computes and Returns the light World matrix.
  21393. * @returns the world matrix
  21394. */
  21395. Light.prototype.getWorldMatrix = function () {
  21396. this._currentRenderId = this.getScene().getRenderId();
  21397. this._childRenderId = this._currentRenderId;
  21398. var worldMatrix = this._getWorldMatrix();
  21399. if (this.parent && this.parent.getWorldMatrix) {
  21400. if (!this._parentedWorldMatrix) {
  21401. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21402. }
  21403. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21404. this._markSyncedWithParent();
  21405. return this._parentedWorldMatrix;
  21406. }
  21407. return worldMatrix;
  21408. };
  21409. /**
  21410. * Sort function to order lights for rendering.
  21411. * @param a First Light object to compare to second.
  21412. * @param b Second Light object to compare first.
  21413. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21414. */
  21415. Light.CompareLightsPriority = function (a, b) {
  21416. //shadow-casting lights have priority over non-shadow-casting lights
  21417. //the renderPrioirty is a secondary sort criterion
  21418. if (a.shadowEnabled !== b.shadowEnabled) {
  21419. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21420. }
  21421. return b.renderPriority - a.renderPriority;
  21422. };
  21423. /**
  21424. * Releases resources associated with this node.
  21425. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21426. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21427. */
  21428. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21429. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21430. if (this._shadowGenerator) {
  21431. this._shadowGenerator.dispose();
  21432. this._shadowGenerator = null;
  21433. }
  21434. // Animations
  21435. this.getScene().stopAnimation(this);
  21436. // Remove from meshes
  21437. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21438. var mesh = _a[_i];
  21439. mesh._removeLightSource(this);
  21440. }
  21441. this._uniformBuffer.dispose();
  21442. // Remove from scene
  21443. this.getScene().removeLight(this);
  21444. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21445. };
  21446. /**
  21447. * Returns the light type ID (integer).
  21448. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21449. */
  21450. Light.prototype.getTypeID = function () {
  21451. return 0;
  21452. };
  21453. /**
  21454. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21455. * @returns the scaled intensity in intensity mode unit
  21456. */
  21457. Light.prototype.getScaledIntensity = function () {
  21458. return this._photometricScale * this.intensity;
  21459. };
  21460. /**
  21461. * Returns a new Light object, named "name", from the current one.
  21462. * @param name The name of the cloned light
  21463. * @returns the new created light
  21464. */
  21465. Light.prototype.clone = function (name) {
  21466. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21467. if (!constructor) {
  21468. return null;
  21469. }
  21470. return BABYLON.SerializationHelper.Clone(constructor, this);
  21471. };
  21472. /**
  21473. * Serializes the current light into a Serialization object.
  21474. * @returns the serialized object.
  21475. */
  21476. Light.prototype.serialize = function () {
  21477. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21478. // Type
  21479. serializationObject.type = this.getTypeID();
  21480. // Parent
  21481. if (this.parent) {
  21482. serializationObject.parentId = this.parent.id;
  21483. }
  21484. // Inclusion / exclusions
  21485. if (this.excludedMeshes.length > 0) {
  21486. serializationObject.excludedMeshesIds = [];
  21487. this.excludedMeshes.forEach(function (mesh) {
  21488. serializationObject.excludedMeshesIds.push(mesh.id);
  21489. });
  21490. }
  21491. if (this.includedOnlyMeshes.length > 0) {
  21492. serializationObject.includedOnlyMeshesIds = [];
  21493. this.includedOnlyMeshes.forEach(function (mesh) {
  21494. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21495. });
  21496. }
  21497. // Animations
  21498. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21499. serializationObject.ranges = this.serializeAnimationRanges();
  21500. return serializationObject;
  21501. };
  21502. /**
  21503. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21504. * This new light is named "name" and added to the passed scene.
  21505. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21506. * @param name The friendly name of the light
  21507. * @param scene The scene the new light will belong to
  21508. * @returns the constructor function
  21509. */
  21510. Light.GetConstructorFromName = function (type, name, scene) {
  21511. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21512. if (constructorFunc) {
  21513. return constructorFunc;
  21514. }
  21515. // Default to no light for none present once.
  21516. return null;
  21517. };
  21518. /**
  21519. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21520. * @param parsedLight The JSON representation of the light
  21521. * @param scene The scene to create the parsed light in
  21522. * @returns the created light after parsing
  21523. */
  21524. Light.Parse = function (parsedLight, scene) {
  21525. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21526. if (!constructor) {
  21527. return null;
  21528. }
  21529. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21530. // Inclusion / exclusions
  21531. if (parsedLight.excludedMeshesIds) {
  21532. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21533. }
  21534. if (parsedLight.includedOnlyMeshesIds) {
  21535. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21536. }
  21537. // Parent
  21538. if (parsedLight.parentId) {
  21539. light._waitingParentId = parsedLight.parentId;
  21540. }
  21541. // Animations
  21542. if (parsedLight.animations) {
  21543. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21544. var parsedAnimation = parsedLight.animations[animationIndex];
  21545. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21546. }
  21547. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21548. }
  21549. if (parsedLight.autoAnimate) {
  21550. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21551. }
  21552. return light;
  21553. };
  21554. Light.prototype._hookArrayForExcluded = function (array) {
  21555. var _this = this;
  21556. var oldPush = array.push;
  21557. array.push = function () {
  21558. var items = [];
  21559. for (var _i = 0; _i < arguments.length; _i++) {
  21560. items[_i] = arguments[_i];
  21561. }
  21562. var result = oldPush.apply(array, items);
  21563. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21564. var item = items_1[_a];
  21565. item._resyncLighSource(_this);
  21566. }
  21567. return result;
  21568. };
  21569. var oldSplice = array.splice;
  21570. array.splice = function (index, deleteCount) {
  21571. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21572. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21573. var item = deleted_1[_i];
  21574. item._resyncLighSource(_this);
  21575. }
  21576. return deleted;
  21577. };
  21578. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21579. var item = array_1[_i];
  21580. item._resyncLighSource(this);
  21581. }
  21582. };
  21583. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21584. var _this = this;
  21585. var oldPush = array.push;
  21586. array.push = function () {
  21587. var items = [];
  21588. for (var _i = 0; _i < arguments.length; _i++) {
  21589. items[_i] = arguments[_i];
  21590. }
  21591. var result = oldPush.apply(array, items);
  21592. _this._resyncMeshes();
  21593. return result;
  21594. };
  21595. var oldSplice = array.splice;
  21596. array.splice = function (index, deleteCount) {
  21597. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21598. _this._resyncMeshes();
  21599. return deleted;
  21600. };
  21601. this._resyncMeshes();
  21602. };
  21603. Light.prototype._resyncMeshes = function () {
  21604. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21605. var mesh = _a[_i];
  21606. mesh._resyncLighSource(this);
  21607. }
  21608. };
  21609. /**
  21610. * Forces the meshes to update their light related information in their rendering used effects
  21611. * @hidden Internal Use Only
  21612. */
  21613. Light.prototype._markMeshesAsLightDirty = function () {
  21614. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21615. var mesh = _a[_i];
  21616. if (mesh._lightSources.indexOf(this) !== -1) {
  21617. mesh._markSubMeshesAsLightDirty();
  21618. }
  21619. }
  21620. };
  21621. /**
  21622. * Recomputes the cached photometric scale if needed.
  21623. */
  21624. Light.prototype._computePhotometricScale = function () {
  21625. this._photometricScale = this._getPhotometricScale();
  21626. this.getScene().resetCachedMaterial();
  21627. };
  21628. /**
  21629. * Returns the Photometric Scale according to the light type and intensity mode.
  21630. */
  21631. Light.prototype._getPhotometricScale = function () {
  21632. var photometricScale = 0.0;
  21633. var lightTypeID = this.getTypeID();
  21634. //get photometric mode
  21635. var photometricMode = this.intensityMode;
  21636. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21637. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21638. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21639. }
  21640. else {
  21641. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21642. }
  21643. }
  21644. //compute photometric scale
  21645. switch (lightTypeID) {
  21646. case Light.LIGHTTYPEID_POINTLIGHT:
  21647. case Light.LIGHTTYPEID_SPOTLIGHT:
  21648. switch (photometricMode) {
  21649. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21650. photometricScale = 1.0 / (4.0 * Math.PI);
  21651. break;
  21652. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21653. photometricScale = 1.0;
  21654. break;
  21655. case Light.INTENSITYMODE_LUMINANCE:
  21656. photometricScale = this.radius * this.radius;
  21657. break;
  21658. }
  21659. break;
  21660. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21661. switch (photometricMode) {
  21662. case Light.INTENSITYMODE_ILLUMINANCE:
  21663. photometricScale = 1.0;
  21664. break;
  21665. case Light.INTENSITYMODE_LUMINANCE:
  21666. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21667. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21668. var apexAngleRadians = this.radius;
  21669. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21670. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21671. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21672. photometricScale = solidAngle;
  21673. break;
  21674. }
  21675. break;
  21676. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21677. // No fall off in hemisperic light.
  21678. photometricScale = 1.0;
  21679. break;
  21680. }
  21681. return photometricScale;
  21682. };
  21683. /**
  21684. * Reorder the light in the scene according to their defined priority.
  21685. * @hidden Internal Use Only
  21686. */
  21687. Light.prototype._reorderLightsInScene = function () {
  21688. var scene = this.getScene();
  21689. if (this._renderPriority != 0) {
  21690. scene.requireLightSorting = true;
  21691. }
  21692. this.getScene().sortLightsByPriority();
  21693. };
  21694. //lightmapMode Consts
  21695. /**
  21696. * If every light affecting the material is in this lightmapMode,
  21697. * material.lightmapTexture adds or multiplies
  21698. * (depends on material.useLightmapAsShadowmap)
  21699. * after every other light calculations.
  21700. */
  21701. Light.LIGHTMAP_DEFAULT = 0;
  21702. /**
  21703. * material.lightmapTexture as only diffuse lighting from this light
  21704. * adds only specular lighting from this light
  21705. * adds dynamic shadows
  21706. */
  21707. Light.LIGHTMAP_SPECULAR = 1;
  21708. /**
  21709. * material.lightmapTexture as only lighting
  21710. * no light calculation from this light
  21711. * only adds dynamic shadows from this light
  21712. */
  21713. Light.LIGHTMAP_SHADOWSONLY = 2;
  21714. // Intensity Mode Consts
  21715. /**
  21716. * Each light type uses the default quantity according to its type:
  21717. * point/spot lights use luminous intensity
  21718. * directional lights use illuminance
  21719. */
  21720. Light.INTENSITYMODE_AUTOMATIC = 0;
  21721. /**
  21722. * lumen (lm)
  21723. */
  21724. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21725. /**
  21726. * candela (lm/sr)
  21727. */
  21728. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21729. /**
  21730. * lux (lm/m^2)
  21731. */
  21732. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21733. /**
  21734. * nit (cd/m^2)
  21735. */
  21736. Light.INTENSITYMODE_LUMINANCE = 4;
  21737. // Light types ids const.
  21738. /**
  21739. * Light type const id of the point light.
  21740. */
  21741. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21742. /**
  21743. * Light type const id of the directional light.
  21744. */
  21745. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21746. /**
  21747. * Light type const id of the spot light.
  21748. */
  21749. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21750. /**
  21751. * Light type const id of the hemispheric light.
  21752. */
  21753. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21754. __decorate([
  21755. BABYLON.serializeAsColor3()
  21756. ], Light.prototype, "diffuse", void 0);
  21757. __decorate([
  21758. BABYLON.serializeAsColor3()
  21759. ], Light.prototype, "specular", void 0);
  21760. __decorate([
  21761. BABYLON.serialize()
  21762. ], Light.prototype, "intensity", void 0);
  21763. __decorate([
  21764. BABYLON.serialize()
  21765. ], Light.prototype, "range", void 0);
  21766. __decorate([
  21767. BABYLON.serialize()
  21768. ], Light.prototype, "intensityMode", null);
  21769. __decorate([
  21770. BABYLON.serialize()
  21771. ], Light.prototype, "radius", null);
  21772. __decorate([
  21773. BABYLON.serialize()
  21774. ], Light.prototype, "_renderPriority", void 0);
  21775. __decorate([
  21776. BABYLON.expandToProperty("_reorderLightsInScene")
  21777. ], Light.prototype, "renderPriority", void 0);
  21778. __decorate([
  21779. BABYLON.serialize("shadowEnabled")
  21780. ], Light.prototype, "_shadowEnabled", void 0);
  21781. __decorate([
  21782. BABYLON.serialize("excludeWithLayerMask")
  21783. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21784. __decorate([
  21785. BABYLON.serialize("includeOnlyWithLayerMask")
  21786. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21787. __decorate([
  21788. BABYLON.serialize("lightmapMode")
  21789. ], Light.prototype, "_lightmapMode", void 0);
  21790. return Light;
  21791. }(BABYLON.Node));
  21792. BABYLON.Light = Light;
  21793. })(BABYLON || (BABYLON = {}));
  21794. //# sourceMappingURL=babylon.light.js.map
  21795. var BABYLON;
  21796. (function (BABYLON) {
  21797. var Camera = /** @class */ (function (_super) {
  21798. __extends(Camera, _super);
  21799. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21800. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21801. var _this = _super.call(this, name, scene) || this;
  21802. /**
  21803. * The vector the camera should consider as up.
  21804. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21805. */
  21806. _this.upVector = BABYLON.Vector3.Up();
  21807. _this.orthoLeft = null;
  21808. _this.orthoRight = null;
  21809. _this.orthoBottom = null;
  21810. _this.orthoTop = null;
  21811. /**
  21812. * FOV is set in Radians. (default is 0.8)
  21813. */
  21814. _this.fov = 0.8;
  21815. _this.minZ = 1;
  21816. _this.maxZ = 10000.0;
  21817. _this.inertia = 0.9;
  21818. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21819. _this.isIntermediate = false;
  21820. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21821. /**
  21822. * Restricts the camera to viewing objects with the same layerMask.
  21823. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21824. */
  21825. _this.layerMask = 0x0FFFFFFF;
  21826. /**
  21827. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21828. */
  21829. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21830. // Camera rig members
  21831. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21832. _this._rigCameras = new Array();
  21833. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21834. _this._skipRendering = false;
  21835. _this.customRenderTargets = new Array();
  21836. // Observables
  21837. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21838. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21839. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21840. _this.onRestoreStateObservable = new BABYLON.Observable();
  21841. // Cache
  21842. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21843. _this._projectionMatrix = new BABYLON.Matrix();
  21844. _this._doNotComputeProjectionMatrix = false;
  21845. _this._worldMatrix = BABYLON.Matrix.Identity();
  21846. _this._postProcesses = new Array();
  21847. _this._transformMatrix = BABYLON.Matrix.Zero();
  21848. _this._activeMeshes = new BABYLON.SmartArray(256);
  21849. _this._globalPosition = BABYLON.Vector3.Zero();
  21850. _this._refreshFrustumPlanes = true;
  21851. _this.getScene().addCamera(_this);
  21852. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21853. _this.getScene().activeCamera = _this;
  21854. }
  21855. _this.position = position;
  21856. return _this;
  21857. }
  21858. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21859. get: function () {
  21860. return Camera._PERSPECTIVE_CAMERA;
  21861. },
  21862. enumerable: true,
  21863. configurable: true
  21864. });
  21865. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21866. get: function () {
  21867. return Camera._ORTHOGRAPHIC_CAMERA;
  21868. },
  21869. enumerable: true,
  21870. configurable: true
  21871. });
  21872. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21873. /**
  21874. * This is the default FOV mode for perspective cameras.
  21875. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21876. *
  21877. */
  21878. get: function () {
  21879. return Camera._FOVMODE_VERTICAL_FIXED;
  21880. },
  21881. enumerable: true,
  21882. configurable: true
  21883. });
  21884. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21885. /**
  21886. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21887. *
  21888. */
  21889. get: function () {
  21890. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21891. },
  21892. enumerable: true,
  21893. configurable: true
  21894. });
  21895. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21896. get: function () {
  21897. return Camera._RIG_MODE_NONE;
  21898. },
  21899. enumerable: true,
  21900. configurable: true
  21901. });
  21902. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21903. get: function () {
  21904. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21905. },
  21906. enumerable: true,
  21907. configurable: true
  21908. });
  21909. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21910. get: function () {
  21911. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21912. },
  21913. enumerable: true,
  21914. configurable: true
  21915. });
  21916. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21917. get: function () {
  21918. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21919. },
  21920. enumerable: true,
  21921. configurable: true
  21922. });
  21923. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21924. get: function () {
  21925. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21926. },
  21927. enumerable: true,
  21928. configurable: true
  21929. });
  21930. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21931. get: function () {
  21932. return Camera._RIG_MODE_VR;
  21933. },
  21934. enumerable: true,
  21935. configurable: true
  21936. });
  21937. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21938. get: function () {
  21939. return Camera._RIG_MODE_WEBVR;
  21940. },
  21941. enumerable: true,
  21942. configurable: true
  21943. });
  21944. /**
  21945. * Store current camera state (fov, position, etc..)
  21946. */
  21947. Camera.prototype.storeState = function () {
  21948. this._stateStored = true;
  21949. this._storedFov = this.fov;
  21950. return this;
  21951. };
  21952. /**
  21953. * Restores the camera state values if it has been stored. You must call storeState() first
  21954. */
  21955. Camera.prototype._restoreStateValues = function () {
  21956. if (!this._stateStored) {
  21957. return false;
  21958. }
  21959. this.fov = this._storedFov;
  21960. return true;
  21961. };
  21962. /**
  21963. * Restored camera state. You must call storeState() first
  21964. */
  21965. Camera.prototype.restoreState = function () {
  21966. if (this._restoreStateValues()) {
  21967. this.onRestoreStateObservable.notifyObservers(this);
  21968. return true;
  21969. }
  21970. return false;
  21971. };
  21972. Camera.prototype.getClassName = function () {
  21973. return "Camera";
  21974. };
  21975. /**
  21976. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21977. */
  21978. Camera.prototype.toString = function (fullDetails) {
  21979. var ret = "Name: " + this.name;
  21980. ret += ", type: " + this.getClassName();
  21981. if (this.animations) {
  21982. for (var i = 0; i < this.animations.length; i++) {
  21983. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21984. }
  21985. }
  21986. if (fullDetails) {
  21987. }
  21988. return ret;
  21989. };
  21990. Object.defineProperty(Camera.prototype, "globalPosition", {
  21991. get: function () {
  21992. return this._globalPosition;
  21993. },
  21994. enumerable: true,
  21995. configurable: true
  21996. });
  21997. Camera.prototype.getActiveMeshes = function () {
  21998. return this._activeMeshes;
  21999. };
  22000. Camera.prototype.isActiveMesh = function (mesh) {
  22001. return (this._activeMeshes.indexOf(mesh) !== -1);
  22002. };
  22003. /**
  22004. * Is this camera ready to be used/rendered
  22005. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22006. * @return true if the camera is ready
  22007. */
  22008. Camera.prototype.isReady = function (completeCheck) {
  22009. if (completeCheck === void 0) { completeCheck = false; }
  22010. if (completeCheck) {
  22011. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22012. var pp = _a[_i];
  22013. if (pp && !pp.isReady()) {
  22014. return false;
  22015. }
  22016. }
  22017. }
  22018. return _super.prototype.isReady.call(this, completeCheck);
  22019. };
  22020. //Cache
  22021. Camera.prototype._initCache = function () {
  22022. _super.prototype._initCache.call(this);
  22023. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22024. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22025. this._cache.mode = undefined;
  22026. this._cache.minZ = undefined;
  22027. this._cache.maxZ = undefined;
  22028. this._cache.fov = undefined;
  22029. this._cache.fovMode = undefined;
  22030. this._cache.aspectRatio = undefined;
  22031. this._cache.orthoLeft = undefined;
  22032. this._cache.orthoRight = undefined;
  22033. this._cache.orthoBottom = undefined;
  22034. this._cache.orthoTop = undefined;
  22035. this._cache.renderWidth = undefined;
  22036. this._cache.renderHeight = undefined;
  22037. };
  22038. Camera.prototype._updateCache = function (ignoreParentClass) {
  22039. if (!ignoreParentClass) {
  22040. _super.prototype._updateCache.call(this);
  22041. }
  22042. this._cache.position.copyFrom(this.position);
  22043. this._cache.upVector.copyFrom(this.upVector);
  22044. };
  22045. // Synchronized
  22046. Camera.prototype._isSynchronized = function () {
  22047. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22048. };
  22049. Camera.prototype._isSynchronizedViewMatrix = function () {
  22050. if (!_super.prototype._isSynchronized.call(this))
  22051. return false;
  22052. return this._cache.position.equals(this.position)
  22053. && this._cache.upVector.equals(this.upVector)
  22054. && this.isSynchronizedWithParent();
  22055. };
  22056. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22057. var check = this._cache.mode === this.mode
  22058. && this._cache.minZ === this.minZ
  22059. && this._cache.maxZ === this.maxZ;
  22060. if (!check) {
  22061. return false;
  22062. }
  22063. var engine = this.getEngine();
  22064. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22065. check = this._cache.fov === this.fov
  22066. && this._cache.fovMode === this.fovMode
  22067. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22068. }
  22069. else {
  22070. check = this._cache.orthoLeft === this.orthoLeft
  22071. && this._cache.orthoRight === this.orthoRight
  22072. && this._cache.orthoBottom === this.orthoBottom
  22073. && this._cache.orthoTop === this.orthoTop
  22074. && this._cache.renderWidth === engine.getRenderWidth()
  22075. && this._cache.renderHeight === engine.getRenderHeight();
  22076. }
  22077. return check;
  22078. };
  22079. // Controls
  22080. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22081. };
  22082. Camera.prototype.detachControl = function (element) {
  22083. };
  22084. Camera.prototype.update = function () {
  22085. this._checkInputs();
  22086. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22087. this._updateRigCameras();
  22088. }
  22089. };
  22090. Camera.prototype._checkInputs = function () {
  22091. this.onAfterCheckInputsObservable.notifyObservers(this);
  22092. };
  22093. Object.defineProperty(Camera.prototype, "rigCameras", {
  22094. get: function () {
  22095. return this._rigCameras;
  22096. },
  22097. enumerable: true,
  22098. configurable: true
  22099. });
  22100. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22101. get: function () {
  22102. return this._rigPostProcess;
  22103. },
  22104. enumerable: true,
  22105. configurable: true
  22106. });
  22107. /**
  22108. * Internal, gets the first post proces.
  22109. * @returns the first post process to be run on this camera.
  22110. */
  22111. Camera.prototype._getFirstPostProcess = function () {
  22112. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22113. if (this._postProcesses[ppIndex] !== null) {
  22114. return this._postProcesses[ppIndex];
  22115. }
  22116. }
  22117. return null;
  22118. };
  22119. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22120. // invalidate framebuffer
  22121. var firstPostProcess = this._getFirstPostProcess();
  22122. if (firstPostProcess) {
  22123. firstPostProcess.markTextureDirty();
  22124. }
  22125. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22126. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22127. var cam = this._rigCameras[i];
  22128. var rigPostProcess = cam._rigPostProcess;
  22129. // for VR rig, there does not have to be a post process
  22130. if (rigPostProcess) {
  22131. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22132. if (isPass) {
  22133. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22134. cam.isIntermediate = this._postProcesses.length === 0;
  22135. }
  22136. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22137. rigPostProcess.markTextureDirty();
  22138. }
  22139. else {
  22140. cam._postProcesses = this._postProcesses.slice(0);
  22141. }
  22142. }
  22143. };
  22144. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22145. if (insertAt === void 0) { insertAt = null; }
  22146. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22147. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22148. return 0;
  22149. }
  22150. if (insertAt == null || insertAt < 0) {
  22151. this._postProcesses.push(postProcess);
  22152. }
  22153. else if (this._postProcesses[insertAt] === null) {
  22154. this._postProcesses[insertAt] = postProcess;
  22155. }
  22156. else {
  22157. this._postProcesses.splice(insertAt, 0, postProcess);
  22158. }
  22159. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22160. return this._postProcesses.indexOf(postProcess);
  22161. };
  22162. Camera.prototype.detachPostProcess = function (postProcess) {
  22163. var idx = this._postProcesses.indexOf(postProcess);
  22164. if (idx !== -1) {
  22165. this._postProcesses[idx] = null;
  22166. }
  22167. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22168. };
  22169. Camera.prototype.getWorldMatrix = function () {
  22170. if (this._isSynchronizedViewMatrix()) {
  22171. return this._worldMatrix;
  22172. }
  22173. // Getting the the view matrix will also compute the world matrix.
  22174. this.getViewMatrix();
  22175. return this._worldMatrix;
  22176. };
  22177. Camera.prototype._getViewMatrix = function () {
  22178. return BABYLON.Matrix.Identity();
  22179. };
  22180. Camera.prototype.getViewMatrix = function (force) {
  22181. if (!force && this._isSynchronizedViewMatrix()) {
  22182. return this._computedViewMatrix;
  22183. }
  22184. this.updateCache();
  22185. this._computedViewMatrix = this._getViewMatrix();
  22186. this._currentRenderId = this.getScene().getRenderId();
  22187. this._childRenderId = this._currentRenderId;
  22188. this._refreshFrustumPlanes = true;
  22189. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22190. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22191. }
  22192. this.onViewMatrixChangedObservable.notifyObservers(this);
  22193. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22194. return this._computedViewMatrix;
  22195. };
  22196. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22197. this._doNotComputeProjectionMatrix = true;
  22198. if (projection !== undefined) {
  22199. this._projectionMatrix = projection;
  22200. }
  22201. };
  22202. ;
  22203. Camera.prototype.unfreezeProjectionMatrix = function () {
  22204. this._doNotComputeProjectionMatrix = false;
  22205. };
  22206. ;
  22207. Camera.prototype.getProjectionMatrix = function (force) {
  22208. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22209. return this._projectionMatrix;
  22210. }
  22211. // Cache
  22212. this._cache.mode = this.mode;
  22213. this._cache.minZ = this.minZ;
  22214. this._cache.maxZ = this.maxZ;
  22215. // Matrix
  22216. this._refreshFrustumPlanes = true;
  22217. var engine = this.getEngine();
  22218. var scene = this.getScene();
  22219. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22220. this._cache.fov = this.fov;
  22221. this._cache.fovMode = this.fovMode;
  22222. this._cache.aspectRatio = engine.getAspectRatio(this);
  22223. if (this.minZ <= 0) {
  22224. this.minZ = 0.1;
  22225. }
  22226. if (scene.useRightHandedSystem) {
  22227. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22228. }
  22229. else {
  22230. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22231. }
  22232. }
  22233. else {
  22234. var halfWidth = engine.getRenderWidth() / 2.0;
  22235. var halfHeight = engine.getRenderHeight() / 2.0;
  22236. if (scene.useRightHandedSystem) {
  22237. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22238. }
  22239. else {
  22240. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22241. }
  22242. this._cache.orthoLeft = this.orthoLeft;
  22243. this._cache.orthoRight = this.orthoRight;
  22244. this._cache.orthoBottom = this.orthoBottom;
  22245. this._cache.orthoTop = this.orthoTop;
  22246. this._cache.renderWidth = engine.getRenderWidth();
  22247. this._cache.renderHeight = engine.getRenderHeight();
  22248. }
  22249. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22250. return this._projectionMatrix;
  22251. };
  22252. Camera.prototype.getTranformationMatrix = function () {
  22253. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22254. return this._transformMatrix;
  22255. };
  22256. Camera.prototype.updateFrustumPlanes = function () {
  22257. if (!this._refreshFrustumPlanes) {
  22258. return;
  22259. }
  22260. this.getTranformationMatrix();
  22261. if (!this._frustumPlanes) {
  22262. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22263. }
  22264. else {
  22265. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22266. }
  22267. this._refreshFrustumPlanes = false;
  22268. };
  22269. Camera.prototype.isInFrustum = function (target) {
  22270. this.updateFrustumPlanes();
  22271. return target.isInFrustum(this._frustumPlanes);
  22272. };
  22273. Camera.prototype.isCompletelyInFrustum = function (target) {
  22274. this.updateFrustumPlanes();
  22275. return target.isCompletelyInFrustum(this._frustumPlanes);
  22276. };
  22277. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22278. if (length === void 0) { length = 100; }
  22279. if (!transform) {
  22280. transform = this.getWorldMatrix();
  22281. }
  22282. if (!origin) {
  22283. origin = this.position;
  22284. }
  22285. var forward = new BABYLON.Vector3(0, 0, 1);
  22286. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22287. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22288. return new BABYLON.Ray(origin, direction, length);
  22289. };
  22290. /**
  22291. * Releases resources associated with this node.
  22292. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22293. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22294. */
  22295. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22296. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22297. // Observables
  22298. this.onViewMatrixChangedObservable.clear();
  22299. this.onProjectionMatrixChangedObservable.clear();
  22300. this.onAfterCheckInputsObservable.clear();
  22301. this.onRestoreStateObservable.clear();
  22302. // Inputs
  22303. if (this.inputs) {
  22304. this.inputs.clear();
  22305. }
  22306. // Animations
  22307. this.getScene().stopAnimation(this);
  22308. // Remove from scene
  22309. this.getScene().removeCamera(this);
  22310. while (this._rigCameras.length > 0) {
  22311. var camera = this._rigCameras.pop();
  22312. if (camera) {
  22313. camera.dispose();
  22314. }
  22315. }
  22316. // Postprocesses
  22317. if (this._rigPostProcess) {
  22318. this._rigPostProcess.dispose(this);
  22319. this._rigPostProcess = null;
  22320. this._postProcesses = [];
  22321. }
  22322. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22323. this._rigPostProcess = null;
  22324. this._postProcesses = [];
  22325. }
  22326. else {
  22327. var i = this._postProcesses.length;
  22328. while (--i >= 0) {
  22329. var postProcess = this._postProcesses[i];
  22330. if (postProcess) {
  22331. postProcess.dispose(this);
  22332. }
  22333. }
  22334. }
  22335. // Render targets
  22336. var i = this.customRenderTargets.length;
  22337. while (--i >= 0) {
  22338. this.customRenderTargets[i].dispose();
  22339. }
  22340. this.customRenderTargets = [];
  22341. // Active Meshes
  22342. this._activeMeshes.dispose();
  22343. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22344. };
  22345. Object.defineProperty(Camera.prototype, "leftCamera", {
  22346. // ---- Camera rigs section ----
  22347. get: function () {
  22348. if (this._rigCameras.length < 1) {
  22349. return null;
  22350. }
  22351. return this._rigCameras[0];
  22352. },
  22353. enumerable: true,
  22354. configurable: true
  22355. });
  22356. Object.defineProperty(Camera.prototype, "rightCamera", {
  22357. get: function () {
  22358. if (this._rigCameras.length < 2) {
  22359. return null;
  22360. }
  22361. return this._rigCameras[1];
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. Camera.prototype.getLeftTarget = function () {
  22367. if (this._rigCameras.length < 1) {
  22368. return null;
  22369. }
  22370. return this._rigCameras[0].getTarget();
  22371. };
  22372. Camera.prototype.getRightTarget = function () {
  22373. if (this._rigCameras.length < 2) {
  22374. return null;
  22375. }
  22376. return this._rigCameras[1].getTarget();
  22377. };
  22378. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22379. if (this.cameraRigMode === mode) {
  22380. return;
  22381. }
  22382. while (this._rigCameras.length > 0) {
  22383. var camera = this._rigCameras.pop();
  22384. if (camera) {
  22385. camera.dispose();
  22386. }
  22387. }
  22388. this.cameraRigMode = mode;
  22389. this._cameraRigParams = {};
  22390. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22391. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22392. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22393. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22394. // create the rig cameras, unless none
  22395. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22396. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22397. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22398. if (leftCamera && rightCamera) {
  22399. this._rigCameras.push(leftCamera);
  22400. this._rigCameras.push(rightCamera);
  22401. }
  22402. }
  22403. switch (this.cameraRigMode) {
  22404. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22405. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22406. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22407. break;
  22408. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22409. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22410. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22411. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22412. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22413. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22414. break;
  22415. case Camera.RIG_MODE_VR:
  22416. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22417. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22418. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22419. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22420. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22421. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22422. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22423. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22424. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22425. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22426. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22427. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22428. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22429. if (metrics.compensateDistortion) {
  22430. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22431. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22432. }
  22433. break;
  22434. case Camera.RIG_MODE_WEBVR:
  22435. if (rigParams.vrDisplay) {
  22436. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22437. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22438. //Left eye
  22439. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22440. this._rigCameras[0].setCameraRigParameter("left", true);
  22441. //leaving this for future reference
  22442. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22443. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22444. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22445. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22446. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22447. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22448. this._rigCameras[0].parent = this;
  22449. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22450. //Right eye
  22451. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22452. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22453. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22454. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22455. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22456. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22457. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22458. this._rigCameras[1].parent = this;
  22459. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22460. if (Camera.UseAlternateWebVRRendering) {
  22461. this._rigCameras[1]._skipRendering = true;
  22462. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22463. }
  22464. }
  22465. break;
  22466. }
  22467. this._cascadePostProcessesToRigCams();
  22468. this.update();
  22469. };
  22470. Camera.prototype._getVRProjectionMatrix = function () {
  22471. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22472. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22473. return this._projectionMatrix;
  22474. };
  22475. Camera.prototype._updateCameraRotationMatrix = function () {
  22476. //Here for WebVR
  22477. };
  22478. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22479. //Here for WebVR
  22480. };
  22481. /**
  22482. * This function MUST be overwritten by the different WebVR cameras available.
  22483. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22484. */
  22485. Camera.prototype._getWebVRProjectionMatrix = function () {
  22486. return BABYLON.Matrix.Identity();
  22487. };
  22488. /**
  22489. * This function MUST be overwritten by the different WebVR cameras available.
  22490. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22491. */
  22492. Camera.prototype._getWebVRViewMatrix = function () {
  22493. return BABYLON.Matrix.Identity();
  22494. };
  22495. Camera.prototype.setCameraRigParameter = function (name, value) {
  22496. if (!this._cameraRigParams) {
  22497. this._cameraRigParams = {};
  22498. }
  22499. this._cameraRigParams[name] = value;
  22500. //provisionnally:
  22501. if (name === "interaxialDistance") {
  22502. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22503. }
  22504. };
  22505. /**
  22506. * needs to be overridden by children so sub has required properties to be copied
  22507. */
  22508. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22509. return null;
  22510. };
  22511. /**
  22512. * May need to be overridden by children
  22513. */
  22514. Camera.prototype._updateRigCameras = function () {
  22515. for (var i = 0; i < this._rigCameras.length; i++) {
  22516. this._rigCameras[i].minZ = this.minZ;
  22517. this._rigCameras[i].maxZ = this.maxZ;
  22518. this._rigCameras[i].fov = this.fov;
  22519. }
  22520. // only update viewport when ANAGLYPH
  22521. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22522. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22523. }
  22524. };
  22525. Camera.prototype._setupInputs = function () {
  22526. };
  22527. Camera.prototype.serialize = function () {
  22528. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22529. // Type
  22530. serializationObject.type = this.getClassName();
  22531. // Parent
  22532. if (this.parent) {
  22533. serializationObject.parentId = this.parent.id;
  22534. }
  22535. if (this.inputs) {
  22536. this.inputs.serialize(serializationObject);
  22537. }
  22538. // Animations
  22539. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22540. serializationObject.ranges = this.serializeAnimationRanges();
  22541. return serializationObject;
  22542. };
  22543. Camera.prototype.clone = function (name) {
  22544. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22545. };
  22546. Camera.prototype.getDirection = function (localAxis) {
  22547. var result = BABYLON.Vector3.Zero();
  22548. this.getDirectionToRef(localAxis, result);
  22549. return result;
  22550. };
  22551. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22552. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22553. };
  22554. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22555. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22556. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22557. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22558. interaxial_distance: interaxial_distance,
  22559. isStereoscopicSideBySide: isStereoscopicSideBySide
  22560. });
  22561. if (constructorFunc) {
  22562. return constructorFunc;
  22563. }
  22564. // Default to universal camera
  22565. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22566. };
  22567. Camera.prototype.computeWorldMatrix = function () {
  22568. return this.getWorldMatrix();
  22569. };
  22570. Camera.Parse = function (parsedCamera, scene) {
  22571. var type = parsedCamera.type;
  22572. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22573. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22574. // Parent
  22575. if (parsedCamera.parentId) {
  22576. camera._waitingParentId = parsedCamera.parentId;
  22577. }
  22578. //If camera has an input manager, let it parse inputs settings
  22579. if (camera.inputs) {
  22580. camera.inputs.parse(parsedCamera);
  22581. camera._setupInputs();
  22582. }
  22583. if (camera.setPosition) { // need to force position
  22584. camera.position.copyFromFloats(0, 0, 0);
  22585. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22586. }
  22587. // Target
  22588. if (parsedCamera.target) {
  22589. if (camera.setTarget) {
  22590. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22591. }
  22592. }
  22593. // Apply 3d rig, when found
  22594. if (parsedCamera.cameraRigMode) {
  22595. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22596. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22597. }
  22598. // Animations
  22599. if (parsedCamera.animations) {
  22600. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22601. var parsedAnimation = parsedCamera.animations[animationIndex];
  22602. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22603. }
  22604. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22605. }
  22606. if (parsedCamera.autoAnimate) {
  22607. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22608. }
  22609. return camera;
  22610. };
  22611. // Statics
  22612. Camera._PERSPECTIVE_CAMERA = 0;
  22613. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22614. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22615. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22616. Camera._RIG_MODE_NONE = 0;
  22617. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22618. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22619. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22620. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22621. Camera._RIG_MODE_VR = 20;
  22622. Camera._RIG_MODE_WEBVR = 21;
  22623. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22624. Camera.UseAlternateWebVRRendering = false;
  22625. __decorate([
  22626. BABYLON.serializeAsVector3()
  22627. ], Camera.prototype, "position", void 0);
  22628. __decorate([
  22629. BABYLON.serializeAsVector3()
  22630. ], Camera.prototype, "upVector", void 0);
  22631. __decorate([
  22632. BABYLON.serialize()
  22633. ], Camera.prototype, "orthoLeft", void 0);
  22634. __decorate([
  22635. BABYLON.serialize()
  22636. ], Camera.prototype, "orthoRight", void 0);
  22637. __decorate([
  22638. BABYLON.serialize()
  22639. ], Camera.prototype, "orthoBottom", void 0);
  22640. __decorate([
  22641. BABYLON.serialize()
  22642. ], Camera.prototype, "orthoTop", void 0);
  22643. __decorate([
  22644. BABYLON.serialize()
  22645. ], Camera.prototype, "fov", void 0);
  22646. __decorate([
  22647. BABYLON.serialize()
  22648. ], Camera.prototype, "minZ", void 0);
  22649. __decorate([
  22650. BABYLON.serialize()
  22651. ], Camera.prototype, "maxZ", void 0);
  22652. __decorate([
  22653. BABYLON.serialize()
  22654. ], Camera.prototype, "inertia", void 0);
  22655. __decorate([
  22656. BABYLON.serialize()
  22657. ], Camera.prototype, "mode", void 0);
  22658. __decorate([
  22659. BABYLON.serialize()
  22660. ], Camera.prototype, "layerMask", void 0);
  22661. __decorate([
  22662. BABYLON.serialize()
  22663. ], Camera.prototype, "fovMode", void 0);
  22664. __decorate([
  22665. BABYLON.serialize()
  22666. ], Camera.prototype, "cameraRigMode", void 0);
  22667. __decorate([
  22668. BABYLON.serialize()
  22669. ], Camera.prototype, "interaxialDistance", void 0);
  22670. __decorate([
  22671. BABYLON.serialize()
  22672. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22673. return Camera;
  22674. }(BABYLON.Node));
  22675. BABYLON.Camera = Camera;
  22676. })(BABYLON || (BABYLON = {}));
  22677. //# sourceMappingURL=babylon.camera.js.map
  22678. var BABYLON;
  22679. (function (BABYLON) {
  22680. var RenderingManager = /** @class */ (function () {
  22681. function RenderingManager(scene) {
  22682. /**
  22683. * Hidden
  22684. */
  22685. this._useSceneAutoClearSetup = false;
  22686. this._renderingGroups = new Array();
  22687. this._autoClearDepthStencil = {};
  22688. this._customOpaqueSortCompareFn = {};
  22689. this._customAlphaTestSortCompareFn = {};
  22690. this._customTransparentSortCompareFn = {};
  22691. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22692. this._scene = scene;
  22693. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22694. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22695. }
  22696. }
  22697. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22698. if (depth === void 0) { depth = true; }
  22699. if (stencil === void 0) { stencil = true; }
  22700. if (this._depthStencilBufferAlreadyCleaned) {
  22701. return;
  22702. }
  22703. this._scene.getEngine().clear(null, false, depth, stencil);
  22704. this._depthStencilBufferAlreadyCleaned = true;
  22705. };
  22706. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22707. // Update the observable context (not null as it only goes away on dispose)
  22708. var info = this._renderingGroupInfo;
  22709. info.scene = this._scene;
  22710. info.camera = this._scene.activeCamera;
  22711. // Dispatch sprites
  22712. if (renderSprites) {
  22713. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22714. var manager = this._scene.spriteManagers[index];
  22715. this.dispatchSprites(manager);
  22716. }
  22717. }
  22718. // Render
  22719. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22720. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22721. var renderingGroup = this._renderingGroups[index];
  22722. if (!renderingGroup)
  22723. continue;
  22724. var renderingGroupMask = Math.pow(2, index);
  22725. info.renderingGroupId = index;
  22726. // Before Observable
  22727. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22728. // Clear depth/stencil if needed
  22729. if (RenderingManager.AUTOCLEAR) {
  22730. var autoClear = this._useSceneAutoClearSetup ?
  22731. this._scene.getAutoClearDepthStencilSetup(index) :
  22732. this._autoClearDepthStencil[index];
  22733. if (autoClear && autoClear.autoClear) {
  22734. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22735. }
  22736. }
  22737. // Render
  22738. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22739. var step = _a[_i];
  22740. step.action(index);
  22741. }
  22742. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22743. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22744. var step = _c[_b];
  22745. step.action(index);
  22746. }
  22747. // After Observable
  22748. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22749. }
  22750. };
  22751. RenderingManager.prototype.reset = function () {
  22752. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22753. var renderingGroup = this._renderingGroups[index];
  22754. if (renderingGroup) {
  22755. renderingGroup.prepare();
  22756. }
  22757. }
  22758. };
  22759. RenderingManager.prototype.dispose = function () {
  22760. this.freeRenderingGroups();
  22761. this._renderingGroups.length = 0;
  22762. this._renderingGroupInfo = null;
  22763. };
  22764. /**
  22765. * Clear the info related to rendering groups preventing retention points during dispose.
  22766. */
  22767. RenderingManager.prototype.freeRenderingGroups = function () {
  22768. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22769. var renderingGroup = this._renderingGroups[index];
  22770. if (renderingGroup) {
  22771. renderingGroup.dispose();
  22772. }
  22773. }
  22774. };
  22775. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22776. if (this._renderingGroups[renderingGroupId] === undefined) {
  22777. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22778. }
  22779. };
  22780. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22781. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22782. this._prepareRenderingGroup(renderingGroupId);
  22783. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22784. };
  22785. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22786. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22787. this._prepareRenderingGroup(renderingGroupId);
  22788. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22789. };
  22790. /**
  22791. * @param subMesh The submesh to dispatch
  22792. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22793. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22794. */
  22795. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22796. if (mesh === undefined) {
  22797. mesh = subMesh.getMesh();
  22798. }
  22799. var renderingGroupId = mesh.renderingGroupId || 0;
  22800. this._prepareRenderingGroup(renderingGroupId);
  22801. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22802. };
  22803. /**
  22804. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22805. * This allowed control for front to back rendering or reversly depending of the special needs.
  22806. *
  22807. * @param renderingGroupId The rendering group id corresponding to its index
  22808. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22809. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22810. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22811. */
  22812. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22813. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22814. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22815. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22816. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22817. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22818. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22819. if (this._renderingGroups[renderingGroupId]) {
  22820. var group = this._renderingGroups[renderingGroupId];
  22821. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22822. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22823. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22824. }
  22825. };
  22826. /**
  22827. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22828. *
  22829. * @param renderingGroupId The rendering group id corresponding to its index
  22830. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22831. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22832. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22833. */
  22834. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22835. if (depth === void 0) { depth = true; }
  22836. if (stencil === void 0) { stencil = true; }
  22837. this._autoClearDepthStencil[renderingGroupId] = {
  22838. autoClear: autoClearDepthStencil,
  22839. depth: depth,
  22840. stencil: stencil
  22841. };
  22842. };
  22843. /**
  22844. * Gets the current auto clear configuration for one rendering group of the rendering
  22845. * manager.
  22846. * @param index the rendering group index to get the information for
  22847. * @returns The auto clear setup for the requested rendering group
  22848. */
  22849. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  22850. return this._autoClearDepthStencil[index];
  22851. };
  22852. /**
  22853. * The max id used for rendering groups (not included)
  22854. */
  22855. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22856. /**
  22857. * The min id used for rendering groups (included)
  22858. */
  22859. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22860. /**
  22861. * Used to globally prevent autoclearing scenes.
  22862. */
  22863. RenderingManager.AUTOCLEAR = true;
  22864. return RenderingManager;
  22865. }());
  22866. BABYLON.RenderingManager = RenderingManager;
  22867. })(BABYLON || (BABYLON = {}));
  22868. //# sourceMappingURL=babylon.renderingManager.js.map
  22869. var BABYLON;
  22870. (function (BABYLON) {
  22871. var RenderingGroup = /** @class */ (function () {
  22872. /**
  22873. * Creates a new rendering group.
  22874. * @param index The rendering group index
  22875. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22876. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22877. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22878. */
  22879. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22880. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22881. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22882. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22883. this.index = index;
  22884. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22885. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22886. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22887. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22888. this._particleSystems = new BABYLON.SmartArray(256);
  22889. this._spriteManagers = new BABYLON.SmartArray(256);
  22890. this._edgesRenderers = new BABYLON.SmartArray(16);
  22891. this._scene = scene;
  22892. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22893. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22894. this.transparentSortCompareFn = transparentSortCompareFn;
  22895. }
  22896. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22897. /**
  22898. * Set the opaque sort comparison function.
  22899. * If null the sub meshes will be render in the order they were created
  22900. */
  22901. set: function (value) {
  22902. this._opaqueSortCompareFn = value;
  22903. if (value) {
  22904. this._renderOpaque = this.renderOpaqueSorted;
  22905. }
  22906. else {
  22907. this._renderOpaque = RenderingGroup.renderUnsorted;
  22908. }
  22909. },
  22910. enumerable: true,
  22911. configurable: true
  22912. });
  22913. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22914. /**
  22915. * Set the alpha test sort comparison function.
  22916. * If null the sub meshes will be render in the order they were created
  22917. */
  22918. set: function (value) {
  22919. this._alphaTestSortCompareFn = value;
  22920. if (value) {
  22921. this._renderAlphaTest = this.renderAlphaTestSorted;
  22922. }
  22923. else {
  22924. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22925. }
  22926. },
  22927. enumerable: true,
  22928. configurable: true
  22929. });
  22930. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22931. /**
  22932. * Set the transparent sort comparison function.
  22933. * If null the sub meshes will be render in the order they were created
  22934. */
  22935. set: function (value) {
  22936. if (value) {
  22937. this._transparentSortCompareFn = value;
  22938. }
  22939. else {
  22940. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22941. }
  22942. this._renderTransparent = this.renderTransparentSorted;
  22943. },
  22944. enumerable: true,
  22945. configurable: true
  22946. });
  22947. /**
  22948. * Render all the sub meshes contained in the group.
  22949. * @param customRenderFunction Used to override the default render behaviour of the group.
  22950. * @returns true if rendered some submeshes.
  22951. */
  22952. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22953. if (customRenderFunction) {
  22954. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22955. return;
  22956. }
  22957. var engine = this._scene.getEngine();
  22958. // Depth only
  22959. if (this._depthOnlySubMeshes.length !== 0) {
  22960. engine.setColorWrite(false);
  22961. this._renderAlphaTest(this._depthOnlySubMeshes);
  22962. engine.setColorWrite(true);
  22963. }
  22964. // Opaque
  22965. if (this._opaqueSubMeshes.length !== 0) {
  22966. this._renderOpaque(this._opaqueSubMeshes);
  22967. }
  22968. // Alpha test
  22969. if (this._alphaTestSubMeshes.length !== 0) {
  22970. this._renderAlphaTest(this._alphaTestSubMeshes);
  22971. }
  22972. var stencilState = engine.getStencilBuffer();
  22973. engine.setStencilBuffer(false);
  22974. // Sprites
  22975. if (renderSprites) {
  22976. this._renderSprites();
  22977. }
  22978. // Particles
  22979. if (renderParticles) {
  22980. this._renderParticles(activeMeshes);
  22981. }
  22982. if (this.onBeforeTransparentRendering) {
  22983. this.onBeforeTransparentRendering();
  22984. }
  22985. // Transparent
  22986. if (this._transparentSubMeshes.length !== 0) {
  22987. this._renderTransparent(this._transparentSubMeshes);
  22988. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22989. }
  22990. // Set back stencil to false in case it changes before the edge renderer.
  22991. engine.setStencilBuffer(false);
  22992. // Edges
  22993. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22994. this._edgesRenderers.data[edgesRendererIndex].render();
  22995. }
  22996. // Restore Stencil state.
  22997. engine.setStencilBuffer(stencilState);
  22998. };
  22999. /**
  23000. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23001. * @param subMeshes The submeshes to render
  23002. */
  23003. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23004. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23005. };
  23006. /**
  23007. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23008. * @param subMeshes The submeshes to render
  23009. */
  23010. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23011. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23012. };
  23013. /**
  23014. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23015. * @param subMeshes The submeshes to render
  23016. */
  23017. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23018. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23019. };
  23020. /**
  23021. * Renders the submeshes in a specified order.
  23022. * @param subMeshes The submeshes to sort before render
  23023. * @param sortCompareFn The comparison function use to sort
  23024. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23025. * @param transparent Specifies to activate blending if true
  23026. */
  23027. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23028. var subIndex = 0;
  23029. var subMesh;
  23030. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23031. for (; subIndex < subMeshes.length; subIndex++) {
  23032. subMesh = subMeshes.data[subIndex];
  23033. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23034. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23035. }
  23036. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23037. if (sortCompareFn) {
  23038. sortedArray.sort(sortCompareFn);
  23039. }
  23040. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23041. subMesh = sortedArray[subIndex];
  23042. if (transparent) {
  23043. var material = subMesh.getMaterial();
  23044. if (material && material.needDepthPrePass) {
  23045. var engine = material.getScene().getEngine();
  23046. engine.setColorWrite(false);
  23047. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23048. subMesh.render(false);
  23049. engine.setColorWrite(true);
  23050. }
  23051. }
  23052. subMesh.render(transparent);
  23053. }
  23054. };
  23055. /**
  23056. * Renders the submeshes in the order they were dispatched (no sort applied).
  23057. * @param subMeshes The submeshes to render
  23058. */
  23059. RenderingGroup.renderUnsorted = function (subMeshes) {
  23060. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23061. var submesh = subMeshes.data[subIndex];
  23062. submesh.render(false);
  23063. }
  23064. };
  23065. /**
  23066. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23067. * are rendered back to front if in the same alpha index.
  23068. *
  23069. * @param a The first submesh
  23070. * @param b The second submesh
  23071. * @returns The result of the comparison
  23072. */
  23073. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23074. // Alpha index first
  23075. if (a._alphaIndex > b._alphaIndex) {
  23076. return 1;
  23077. }
  23078. if (a._alphaIndex < b._alphaIndex) {
  23079. return -1;
  23080. }
  23081. // Then distance to camera
  23082. return RenderingGroup.backToFrontSortCompare(a, b);
  23083. };
  23084. /**
  23085. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23086. * are rendered back to front.
  23087. *
  23088. * @param a The first submesh
  23089. * @param b The second submesh
  23090. * @returns The result of the comparison
  23091. */
  23092. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23093. // Then distance to camera
  23094. if (a._distanceToCamera < b._distanceToCamera) {
  23095. return 1;
  23096. }
  23097. if (a._distanceToCamera > b._distanceToCamera) {
  23098. return -1;
  23099. }
  23100. return 0;
  23101. };
  23102. /**
  23103. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23104. * are rendered front to back (prevent overdraw).
  23105. *
  23106. * @param a The first submesh
  23107. * @param b The second submesh
  23108. * @returns The result of the comparison
  23109. */
  23110. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23111. // Then distance to camera
  23112. if (a._distanceToCamera < b._distanceToCamera) {
  23113. return -1;
  23114. }
  23115. if (a._distanceToCamera > b._distanceToCamera) {
  23116. return 1;
  23117. }
  23118. return 0;
  23119. };
  23120. /**
  23121. * Resets the different lists of submeshes to prepare a new frame.
  23122. */
  23123. RenderingGroup.prototype.prepare = function () {
  23124. this._opaqueSubMeshes.reset();
  23125. this._transparentSubMeshes.reset();
  23126. this._alphaTestSubMeshes.reset();
  23127. this._depthOnlySubMeshes.reset();
  23128. this._particleSystems.reset();
  23129. this._spriteManagers.reset();
  23130. this._edgesRenderers.reset();
  23131. };
  23132. RenderingGroup.prototype.dispose = function () {
  23133. this._opaqueSubMeshes.dispose();
  23134. this._transparentSubMeshes.dispose();
  23135. this._alphaTestSubMeshes.dispose();
  23136. this._depthOnlySubMeshes.dispose();
  23137. this._particleSystems.dispose();
  23138. this._spriteManagers.dispose();
  23139. this._edgesRenderers.dispose();
  23140. };
  23141. /**
  23142. * Inserts the submesh in its correct queue depending on its material.
  23143. * @param subMesh The submesh to dispatch
  23144. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23145. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23146. */
  23147. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23148. // Get mesh and materials if not provided
  23149. if (mesh === undefined) {
  23150. mesh = subMesh.getMesh();
  23151. }
  23152. if (material === undefined) {
  23153. material = subMesh.getMaterial();
  23154. }
  23155. if (material === null || material === undefined) {
  23156. return;
  23157. }
  23158. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23159. this._transparentSubMeshes.push(subMesh);
  23160. }
  23161. else if (material.needAlphaTesting()) { // Alpha test
  23162. if (material.needDepthPrePass) {
  23163. this._depthOnlySubMeshes.push(subMesh);
  23164. }
  23165. this._alphaTestSubMeshes.push(subMesh);
  23166. }
  23167. else {
  23168. if (material.needDepthPrePass) {
  23169. this._depthOnlySubMeshes.push(subMesh);
  23170. }
  23171. this._opaqueSubMeshes.push(subMesh); // Opaque
  23172. }
  23173. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23174. this._edgesRenderers.push(mesh._edgesRenderer);
  23175. }
  23176. };
  23177. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23178. this._spriteManagers.push(spriteManager);
  23179. };
  23180. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23181. this._particleSystems.push(particleSystem);
  23182. };
  23183. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23184. if (this._particleSystems.length === 0) {
  23185. return;
  23186. }
  23187. // Particles
  23188. var activeCamera = this._scene.activeCamera;
  23189. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23190. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23191. var particleSystem = this._particleSystems.data[particleIndex];
  23192. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23193. continue;
  23194. }
  23195. var emitter = particleSystem.emitter;
  23196. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23197. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23198. }
  23199. }
  23200. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23201. };
  23202. RenderingGroup.prototype._renderSprites = function () {
  23203. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23204. return;
  23205. }
  23206. // Sprites
  23207. var activeCamera = this._scene.activeCamera;
  23208. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23209. for (var id = 0; id < this._spriteManagers.length; id++) {
  23210. var spriteManager = this._spriteManagers.data[id];
  23211. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23212. spriteManager.render();
  23213. }
  23214. }
  23215. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23216. };
  23217. return RenderingGroup;
  23218. }());
  23219. BABYLON.RenderingGroup = RenderingGroup;
  23220. })(BABYLON || (BABYLON = {}));
  23221. //# sourceMappingURL=babylon.renderingGroup.js.map
  23222. var BABYLON;
  23223. (function (BABYLON) {
  23224. /**
  23225. * Groups all the scene component constants in one place to ease maintenance.
  23226. * @hidden
  23227. */
  23228. var SceneComponentConstants = /** @class */ (function () {
  23229. function SceneComponentConstants() {
  23230. }
  23231. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23232. SceneComponentConstants.NAME_LAYER = "Layer";
  23233. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23234. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23235. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23236. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23237. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23238. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23239. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23240. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23241. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23242. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23243. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23244. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23245. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23246. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23247. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23248. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23249. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23250. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23251. return SceneComponentConstants;
  23252. }());
  23253. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23254. /**
  23255. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23256. * @hidden
  23257. */
  23258. var Stage = /** @class */ (function (_super) {
  23259. __extends(Stage, _super);
  23260. /**
  23261. * Hide ctor from the rest of the world.
  23262. * @param items The items to add.
  23263. */
  23264. function Stage(items) {
  23265. return _super.apply(this, items) || this;
  23266. }
  23267. /**
  23268. * Creates a new Stage.
  23269. * @returns A new instance of a Stage
  23270. */
  23271. Stage.Create = function () {
  23272. return Object.create(Stage.prototype);
  23273. };
  23274. /**
  23275. * Registers a step in an ordered way in the targeted stage.
  23276. * @param index Defines the position to register the step in
  23277. * @param component Defines the component attached to the step
  23278. * @param action Defines the action to launch during the step
  23279. */
  23280. Stage.prototype.registerStep = function (index, component, action) {
  23281. var i = 0;
  23282. var maxIndex = Number.MAX_VALUE;
  23283. for (; i < this.length && i < maxIndex; i++) {
  23284. var step = this[i];
  23285. maxIndex = step.index;
  23286. }
  23287. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23288. };
  23289. /**
  23290. * Clears all the steps from the stage.
  23291. */
  23292. Stage.prototype.clear = function () {
  23293. this.length = 0;
  23294. };
  23295. return Stage;
  23296. }(Array));
  23297. BABYLON.Stage = Stage;
  23298. })(BABYLON || (BABYLON = {}));
  23299. //# sourceMappingURL=babylon.sceneComponent.js.map
  23300. var BABYLON;
  23301. (function (BABYLON) {
  23302. /**
  23303. * Base class of the scene acting as a container for the different elements composing a scene.
  23304. * This class is dynamically extended by the different components of the scene increasing
  23305. * flexibility and reducing coupling
  23306. */
  23307. var AbstractScene = /** @class */ (function () {
  23308. function AbstractScene() {
  23309. /** All of the cameras added to this scene
  23310. * @see http://doc.babylonjs.com/babylon101/cameras
  23311. */
  23312. this.cameras = new Array();
  23313. /**
  23314. * All of the lights added to this scene
  23315. * @see http://doc.babylonjs.com/babylon101/lights
  23316. */
  23317. this.lights = new Array();
  23318. /**
  23319. * All of the (abstract) meshes added to this scene
  23320. */
  23321. this.meshes = new Array();
  23322. /**
  23323. * The list of skeletons added to the scene
  23324. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23325. */
  23326. this.skeletons = new Array();
  23327. /**
  23328. * All of the particle systems added to this scene
  23329. * @see http://doc.babylonjs.com/babylon101/particles
  23330. */
  23331. this.particleSystems = new Array();
  23332. /**
  23333. * Gets a list of Animations associated with the scene
  23334. */
  23335. this.animations = [];
  23336. /**
  23337. * All of the animation groups added to this scene
  23338. * @see http://doc.babylonjs.com/how_to/group
  23339. */
  23340. this.animationGroups = new Array();
  23341. /**
  23342. * All of the multi-materials added to this scene
  23343. * @see http://doc.babylonjs.com/how_to/multi_materials
  23344. */
  23345. this.multiMaterials = new Array();
  23346. /**
  23347. * All of the materials added to this scene
  23348. * @see http://doc.babylonjs.com/babylon101/materials
  23349. */
  23350. this.materials = new Array();
  23351. /**
  23352. * The list of morph target managers added to the scene
  23353. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23354. */
  23355. this.morphTargetManagers = new Array();
  23356. /**
  23357. * The list of geometries used in the scene.
  23358. */
  23359. this.geometries = new Array();
  23360. /**
  23361. * All of the tranform nodes added to this scene
  23362. * @see http://doc.babylonjs.com/how_to/transformnode
  23363. */
  23364. this.transformNodes = new Array();
  23365. /**
  23366. * ActionManagers available on the scene.
  23367. */
  23368. this.actionManagers = new Array();
  23369. /**
  23370. * Sounds to keep.
  23371. */
  23372. this.sounds = new Array();
  23373. /**
  23374. * Textures to keep.
  23375. */
  23376. this.textures = new Array();
  23377. }
  23378. /**
  23379. * Adds a parser in the list of available ones
  23380. * @param name Defines the name of the parser
  23381. * @param parser Defines the parser to add
  23382. */
  23383. AbstractScene.AddParser = function (name, parser) {
  23384. this._BabylonFileParsers[name] = parser;
  23385. };
  23386. /**
  23387. * Gets a general parser from the list of avaialble ones
  23388. * @param name Defines the name of the parser
  23389. * @returns the requested parser or null
  23390. */
  23391. AbstractScene.GetParser = function (name) {
  23392. if (this._BabylonFileParsers[name]) {
  23393. return this._BabylonFileParsers[name];
  23394. }
  23395. return null;
  23396. };
  23397. /**
  23398. * Adds n individual parser in the list of available ones
  23399. * @param name Defines the name of the parser
  23400. * @param parser Defines the parser to add
  23401. */
  23402. AbstractScene.AddIndividualParser = function (name, parser) {
  23403. this._IndividualBabylonFileParsers[name] = parser;
  23404. };
  23405. /**
  23406. * Gets an individual parser from the list of avaialble ones
  23407. * @param name Defines the name of the parser
  23408. * @returns the requested parser or null
  23409. */
  23410. AbstractScene.GetIndividualParser = function (name) {
  23411. if (this._IndividualBabylonFileParsers[name]) {
  23412. return this._IndividualBabylonFileParsers[name];
  23413. }
  23414. return null;
  23415. };
  23416. /**
  23417. * Parser json data and populate both a scene and its associated container object
  23418. * @param jsonData Defines the data to parse
  23419. * @param scene Defines the scene to parse the data for
  23420. * @param container Defines the container attached to the parsing sequence
  23421. * @param rootUrl Defines the root url of the data
  23422. */
  23423. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23424. for (var parserName in this._BabylonFileParsers) {
  23425. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23426. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23427. }
  23428. }
  23429. };
  23430. /**
  23431. * Stores the list of available parsers in the application.
  23432. */
  23433. AbstractScene._BabylonFileParsers = {};
  23434. /**
  23435. * Stores the list of available individual parsers in the application.
  23436. */
  23437. AbstractScene._IndividualBabylonFileParsers = {};
  23438. return AbstractScene;
  23439. }());
  23440. BABYLON.AbstractScene = AbstractScene;
  23441. })(BABYLON || (BABYLON = {}));
  23442. //# sourceMappingURL=babylon.abstractScene.js.map
  23443. var BABYLON;
  23444. (function (BABYLON) {
  23445. /** @hidden */
  23446. var ClickInfo = /** @class */ (function () {
  23447. function ClickInfo() {
  23448. this._singleClick = false;
  23449. this._doubleClick = false;
  23450. this._hasSwiped = false;
  23451. this._ignore = false;
  23452. }
  23453. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23454. get: function () {
  23455. return this._singleClick;
  23456. },
  23457. set: function (b) {
  23458. this._singleClick = b;
  23459. },
  23460. enumerable: true,
  23461. configurable: true
  23462. });
  23463. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23464. get: function () {
  23465. return this._doubleClick;
  23466. },
  23467. set: function (b) {
  23468. this._doubleClick = b;
  23469. },
  23470. enumerable: true,
  23471. configurable: true
  23472. });
  23473. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23474. get: function () {
  23475. return this._hasSwiped;
  23476. },
  23477. set: function (b) {
  23478. this._hasSwiped = b;
  23479. },
  23480. enumerable: true,
  23481. configurable: true
  23482. });
  23483. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23484. get: function () {
  23485. return this._ignore;
  23486. },
  23487. set: function (b) {
  23488. this._ignore = b;
  23489. },
  23490. enumerable: true,
  23491. configurable: true
  23492. });
  23493. return ClickInfo;
  23494. }());
  23495. /**
  23496. * This class is used by the onRenderingGroupObservable
  23497. */
  23498. var RenderingGroupInfo = /** @class */ (function () {
  23499. function RenderingGroupInfo() {
  23500. }
  23501. return RenderingGroupInfo;
  23502. }());
  23503. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23504. /**
  23505. * Represents a scene to be rendered by the engine.
  23506. * @see http://doc.babylonjs.com/features/scene
  23507. */
  23508. var Scene = /** @class */ (function (_super) {
  23509. __extends(Scene, _super);
  23510. /**
  23511. * Creates a new Scene
  23512. * @param engine defines the engine to use to render this scene
  23513. */
  23514. function Scene(engine) {
  23515. var _this = _super.call(this) || this;
  23516. // Members
  23517. /**
  23518. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23519. */
  23520. _this.autoClear = true;
  23521. /**
  23522. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23523. */
  23524. _this.autoClearDepthAndStencil = true;
  23525. /**
  23526. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23527. */
  23528. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23529. /**
  23530. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23531. */
  23532. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23533. _this._forceWireframe = false;
  23534. _this._forcePointsCloud = false;
  23535. /**
  23536. * Gets or sets a boolean indicating if animations are enabled
  23537. */
  23538. _this.animationsEnabled = true;
  23539. _this._animationPropertiesOverride = null;
  23540. /**
  23541. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23542. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23543. */
  23544. _this.useConstantAnimationDeltaTime = false;
  23545. /**
  23546. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23547. * Please note that it requires to run a ray cast through the scene on every frame
  23548. */
  23549. _this.constantlyUpdateMeshUnderPointer = false;
  23550. /**
  23551. * Defines the HTML cursor to use when hovering over interactive elements
  23552. */
  23553. _this.hoverCursor = "pointer";
  23554. /**
  23555. * Defines the HTML default cursor to use (empty by default)
  23556. */
  23557. _this.defaultCursor = "";
  23558. /**
  23559. * This is used to call preventDefault() on pointer down
  23560. * in order to block unwanted artifacts like system double clicks
  23561. */
  23562. _this.preventDefaultOnPointerDown = true;
  23563. // Metadata
  23564. /**
  23565. * Gets or sets user defined metadata
  23566. */
  23567. _this.metadata = null;
  23568. /**
  23569. * Use this array to add regular expressions used to disable offline support for specific urls
  23570. */
  23571. _this.disableOfflineSupportExceptionRules = new Array();
  23572. /**
  23573. * An event triggered when the scene is disposed.
  23574. */
  23575. _this.onDisposeObservable = new BABYLON.Observable();
  23576. _this._onDisposeObserver = null;
  23577. /**
  23578. * An event triggered before rendering the scene (right after animations and physics)
  23579. */
  23580. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23581. _this._onBeforeRenderObserver = null;
  23582. /**
  23583. * An event triggered after rendering the scene
  23584. */
  23585. _this.onAfterRenderObservable = new BABYLON.Observable();
  23586. _this._onAfterRenderObserver = null;
  23587. /**
  23588. * An event triggered before animating the scene
  23589. */
  23590. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23591. /**
  23592. * An event triggered after animations processing
  23593. */
  23594. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23595. /**
  23596. * An event triggered before draw calls are ready to be sent
  23597. */
  23598. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23599. /**
  23600. * An event triggered after draw calls have been sent
  23601. */
  23602. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23603. /**
  23604. * An event triggered when physic simulation is about to be run
  23605. */
  23606. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23607. /**
  23608. * An event triggered when physic simulation has been done
  23609. */
  23610. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23611. /**
  23612. * An event triggered when the scene is ready
  23613. */
  23614. _this.onReadyObservable = new BABYLON.Observable();
  23615. /**
  23616. * An event triggered before rendering a camera
  23617. */
  23618. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23619. _this._onBeforeCameraRenderObserver = null;
  23620. /**
  23621. * An event triggered after rendering a camera
  23622. */
  23623. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23624. _this._onAfterCameraRenderObserver = null;
  23625. /**
  23626. * An event triggered when active meshes evaluation is about to start
  23627. */
  23628. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23629. /**
  23630. * An event triggered when active meshes evaluation is done
  23631. */
  23632. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23633. /**
  23634. * An event triggered when particles rendering is about to start
  23635. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23636. */
  23637. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23638. /**
  23639. * An event triggered when particles rendering is done
  23640. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23641. */
  23642. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23643. /**
  23644. * An event triggered when sprites rendering is about to start
  23645. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23646. */
  23647. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23648. /**
  23649. * An event triggered when sprites rendering is done
  23650. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23651. */
  23652. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23653. /**
  23654. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23655. */
  23656. _this.onDataLoadedObservable = new BABYLON.Observable();
  23657. /**
  23658. * An event triggered when a camera is created
  23659. */
  23660. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23661. /**
  23662. * An event triggered when a camera is removed
  23663. */
  23664. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23665. /**
  23666. * An event triggered when a light is created
  23667. */
  23668. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23669. /**
  23670. * An event triggered when a light is removed
  23671. */
  23672. _this.onLightRemovedObservable = new BABYLON.Observable();
  23673. /**
  23674. * An event triggered when a geometry is created
  23675. */
  23676. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23677. /**
  23678. * An event triggered when a geometry is removed
  23679. */
  23680. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23681. /**
  23682. * An event triggered when a transform node is created
  23683. */
  23684. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23685. /**
  23686. * An event triggered when a transform node is removed
  23687. */
  23688. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23689. /**
  23690. * An event triggered when a mesh is created
  23691. */
  23692. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23693. /**
  23694. * An event triggered when a mesh is removed
  23695. */
  23696. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23697. /**
  23698. * An event triggered when render targets are about to be rendered
  23699. * Can happen multiple times per frame.
  23700. */
  23701. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered when render targets were rendered.
  23704. * Can happen multiple times per frame.
  23705. */
  23706. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23707. /**
  23708. * An event triggered before calculating deterministic simulation step
  23709. */
  23710. _this.onBeforeStepObservable = new BABYLON.Observable();
  23711. /**
  23712. * An event triggered after calculating deterministic simulation step
  23713. */
  23714. _this.onAfterStepObservable = new BABYLON.Observable();
  23715. /**
  23716. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  23717. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23718. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  23719. */
  23720. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23721. /**
  23722. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23723. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23724. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  23725. */
  23726. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23727. // Animations
  23728. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23729. /**
  23730. * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
  23731. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23732. */
  23733. _this.onPrePointerObservable = new BABYLON.Observable();
  23734. /**
  23735. * Observable event triggered each time an input event is received from the rendering canvas
  23736. */
  23737. _this.onPointerObservable = new BABYLON.Observable();
  23738. _this._meshPickProceed = false;
  23739. _this._currentPickResult = null;
  23740. _this._previousPickResult = null;
  23741. _this._totalPointersPressed = 0;
  23742. _this._doubleClickOccured = false;
  23743. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23744. _this.cameraToUseForPointers = null;
  23745. _this._pointerX = 0;
  23746. _this._pointerY = 0;
  23747. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23748. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23749. _this._startingPointerTime = 0;
  23750. _this._previousStartingPointerTime = 0;
  23751. _this._pointerCaptures = {};
  23752. // Deterministic lockstep
  23753. _this._timeAccumulator = 0;
  23754. _this._currentStepId = 0;
  23755. _this._currentInternalStep = 0;
  23756. // Keyboard
  23757. /**
  23758. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23759. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23760. */
  23761. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23762. /**
  23763. * Observable event triggered each time an keyboard event is received from the hosting window
  23764. */
  23765. _this.onKeyboardObservable = new BABYLON.Observable();
  23766. // Coordinates system
  23767. _this._useRightHandedSystem = false;
  23768. // Fog
  23769. _this._fogEnabled = true;
  23770. _this._fogMode = Scene.FOGMODE_NONE;
  23771. /**
  23772. * Gets or sets the fog color to use
  23773. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23774. */
  23775. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23776. /**
  23777. * Gets or sets the fog density to use
  23778. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23779. */
  23780. _this.fogDensity = 0.1;
  23781. /**
  23782. * Gets or sets the fog start distance to use
  23783. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23784. */
  23785. _this.fogStart = 0;
  23786. /**
  23787. * Gets or sets the fog end distance to use
  23788. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23789. */
  23790. _this.fogEnd = 1000.0;
  23791. // Lights
  23792. _this._shadowsEnabled = true;
  23793. _this._lightsEnabled = true;
  23794. /** All of the active cameras added to this scene. */
  23795. _this.activeCameras = new Array();
  23796. // Textures
  23797. _this._texturesEnabled = true;
  23798. // Particles
  23799. /**
  23800. * Gets or sets a boolean indicating if particles are enabled on this scene
  23801. */
  23802. _this.particlesEnabled = true;
  23803. // Sprites
  23804. /**
  23805. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23806. */
  23807. _this.spritesEnabled = true;
  23808. /**
  23809. * All of the sprite managers added to this scene
  23810. * @see http://doc.babylonjs.com/babylon101/sprites
  23811. */
  23812. _this.spriteManagers = new Array();
  23813. // Skeletons
  23814. _this._skeletonsEnabled = true;
  23815. // Lens flares
  23816. /**
  23817. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23818. */
  23819. _this.lensFlaresEnabled = true;
  23820. // Collisions
  23821. /**
  23822. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23823. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23824. */
  23825. _this.collisionsEnabled = true;
  23826. /**
  23827. * Defines the gravity applied to this scene (used only for collisions)
  23828. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23829. */
  23830. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23831. // Postprocesses
  23832. /**
  23833. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23834. */
  23835. _this.postProcessesEnabled = true;
  23836. /**
  23837. * The list of postprocesses added to the scene
  23838. */
  23839. _this.postProcesses = new Array();
  23840. // Customs render targets
  23841. /**
  23842. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23843. */
  23844. _this.renderTargetsEnabled = true;
  23845. /**
  23846. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23847. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23848. */
  23849. _this.dumpNextRenderTargets = false;
  23850. /**
  23851. * The list of user defined render targets added to the scene
  23852. */
  23853. _this.customRenderTargets = new Array();
  23854. /**
  23855. * Gets the list of meshes imported to the scene through SceneLoader
  23856. */
  23857. _this.importedMeshesFiles = new Array();
  23858. // Probes
  23859. /**
  23860. * Gets or sets a boolean indicating if probes are enabled on this scene
  23861. */
  23862. _this.probesEnabled = true;
  23863. /**
  23864. * The list of reflection probes added to the scene
  23865. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23866. */
  23867. _this.reflectionProbes = new Array();
  23868. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23869. // Procedural textures
  23870. /**
  23871. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23872. */
  23873. _this.proceduralTexturesEnabled = true;
  23874. /**
  23875. * The list of procedural textures added to the scene
  23876. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23877. */
  23878. _this.proceduralTextures = new Array();
  23879. /**
  23880. * The list of sound tracks added to the scene
  23881. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23882. */
  23883. _this.soundTracks = new Array();
  23884. _this._audioEnabled = true;
  23885. _this._headphone = false;
  23886. // Performance counters
  23887. _this._totalVertices = new BABYLON.PerfCounter();
  23888. /** @hidden */
  23889. _this._activeIndices = new BABYLON.PerfCounter();
  23890. /** @hidden */
  23891. _this._activeParticles = new BABYLON.PerfCounter();
  23892. /** @hidden */
  23893. _this._activeBones = new BABYLON.PerfCounter();
  23894. _this._animationTime = 0;
  23895. /**
  23896. * Gets or sets a general scale for animation speed
  23897. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23898. */
  23899. _this.animationTimeScale = 1;
  23900. _this._renderId = 0;
  23901. _this._executeWhenReadyTimeoutId = -1;
  23902. _this._intermediateRendering = false;
  23903. _this._viewUpdateFlag = -1;
  23904. _this._projectionUpdateFlag = -1;
  23905. _this._alternateViewUpdateFlag = -1;
  23906. _this._alternateProjectionUpdateFlag = -1;
  23907. /** @hidden */
  23908. _this._toBeDisposed = new BABYLON.SmartArray(256);
  23909. _this._activeRequests = new Array();
  23910. _this._pendingData = new Array();
  23911. _this._isDisposed = false;
  23912. /**
  23913. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23914. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23915. */
  23916. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  23917. _this._activeMeshes = new BABYLON.SmartArray(256);
  23918. _this._processedMaterials = new BABYLON.SmartArray(256);
  23919. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23920. /** @hidden */
  23921. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  23922. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23923. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23924. /** @hidden */
  23925. _this._activeAnimatables = new Array();
  23926. _this._transformMatrix = BABYLON.Matrix.Zero();
  23927. _this._useAlternateCameraConfiguration = false;
  23928. _this._alternateRendering = false;
  23929. /**
  23930. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23931. * This is useful if there are more lights that the maximum simulteanous authorized
  23932. */
  23933. _this.requireLightSorting = false;
  23934. _this._depthRenderer = {};
  23935. /**
  23936. * Backing store of defined scene components.
  23937. */
  23938. _this._components = [];
  23939. /**
  23940. * Backing store of defined scene components.
  23941. */
  23942. _this._serializableComponents = [];
  23943. /**
  23944. * List of components to register on the next registration step.
  23945. */
  23946. _this._transientComponents = [];
  23947. /**
  23948. * Defines the actions happening before camera updates.
  23949. */
  23950. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  23951. /**
  23952. * Defines the actions happening during the per mesh ready checks.
  23953. */
  23954. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  23955. /**
  23956. * Defines the actions happening before evaluate active mesh checks.
  23957. */
  23958. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  23959. /**
  23960. * Defines the actions happening during the evaluate sub mesh checks.
  23961. */
  23962. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  23963. /**
  23964. * Defines the actions happening during the active mesh stage.
  23965. */
  23966. _this._activeMeshStage = BABYLON.Stage.Create();
  23967. /**
  23968. * Defines the actions happening during the per camera render target step.
  23969. */
  23970. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  23971. /**
  23972. * Defines the actions happening just before the active camera is drawing.
  23973. */
  23974. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  23975. /**
  23976. * Defines the actions happening just before a rendering group is drawing.
  23977. */
  23978. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  23979. /**
  23980. * Defines the actions happening just after a rendering group has been drawn.
  23981. */
  23982. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  23983. /**
  23984. * Defines the actions happening just after the active camera has been drawn.
  23985. */
  23986. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  23987. _this._activeMeshesFrozen = false;
  23988. /** @hidden */
  23989. _this._allowPostProcessClear = true;
  23990. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23991. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23992. _this._engine.scenes.push(_this);
  23993. _this._uid = null;
  23994. _this._renderingManager = new BABYLON.RenderingManager(_this);
  23995. if (BABYLON.PostProcessManager) {
  23996. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  23997. }
  23998. if (BABYLON.OutlineRenderer) {
  23999. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24000. }
  24001. if (BABYLON.Tools.IsWindowObjectExist()) {
  24002. _this.attachControl();
  24003. }
  24004. //simplification queue
  24005. if (BABYLON.SimplificationQueue) {
  24006. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24007. }
  24008. //collision coordinator initialization. For now legacy per default.
  24009. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24010. // Uniform Buffer
  24011. _this._createUbo();
  24012. // Default Image processing definition
  24013. if (BABYLON.ImageProcessingConfiguration) {
  24014. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24015. }
  24016. return _this;
  24017. }
  24018. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24019. /** The fog is deactivated */
  24020. get: function () {
  24021. return Scene._FOGMODE_NONE;
  24022. },
  24023. enumerable: true,
  24024. configurable: true
  24025. });
  24026. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24027. /** The fog density is following an exponential function */
  24028. get: function () {
  24029. return Scene._FOGMODE_EXP;
  24030. },
  24031. enumerable: true,
  24032. configurable: true
  24033. });
  24034. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24035. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24036. get: function () {
  24037. return Scene._FOGMODE_EXP2;
  24038. },
  24039. enumerable: true,
  24040. configurable: true
  24041. });
  24042. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24043. /** The fog density is following a linear function. */
  24044. get: function () {
  24045. return Scene._FOGMODE_LINEAR;
  24046. },
  24047. enumerable: true,
  24048. configurable: true
  24049. });
  24050. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24051. /**
  24052. * Texture used in all pbr material as the reflection texture.
  24053. * As in the majority of the scene they are the same (exception for multi room and so on),
  24054. * this is easier to reference from here than from all the materials.
  24055. */
  24056. get: function () {
  24057. return this._environmentTexture;
  24058. },
  24059. /**
  24060. * Texture used in all pbr material as the reflection texture.
  24061. * As in the majority of the scene they are the same (exception for multi room and so on),
  24062. * this is easier to set here than in all the materials.
  24063. */
  24064. set: function (value) {
  24065. if (this._environmentTexture === value) {
  24066. return;
  24067. }
  24068. this._environmentTexture = value;
  24069. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24070. },
  24071. enumerable: true,
  24072. configurable: true
  24073. });
  24074. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24075. /**
  24076. * Default image processing configuration used either in the rendering
  24077. * Forward main pass or through the imageProcessingPostProcess if present.
  24078. * As in the majority of the scene they are the same (exception for multi camera),
  24079. * this is easier to reference from here than from all the materials and post process.
  24080. *
  24081. * No setter as we it is a shared configuration, you can set the values instead.
  24082. */
  24083. get: function () {
  24084. return this._imageProcessingConfiguration;
  24085. },
  24086. enumerable: true,
  24087. configurable: true
  24088. });
  24089. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24090. get: function () {
  24091. return this._forceWireframe;
  24092. },
  24093. /**
  24094. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24095. */
  24096. set: function (value) {
  24097. if (this._forceWireframe === value) {
  24098. return;
  24099. }
  24100. this._forceWireframe = value;
  24101. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24102. },
  24103. enumerable: true,
  24104. configurable: true
  24105. });
  24106. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24107. get: function () {
  24108. return this._forcePointsCloud;
  24109. },
  24110. /**
  24111. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24112. */
  24113. set: function (value) {
  24114. if (this._forcePointsCloud === value) {
  24115. return;
  24116. }
  24117. this._forcePointsCloud = value;
  24118. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24119. },
  24120. enumerable: true,
  24121. configurable: true
  24122. });
  24123. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24124. /**
  24125. * Gets or sets the animation properties override
  24126. */
  24127. get: function () {
  24128. return this._animationPropertiesOverride;
  24129. },
  24130. set: function (value) {
  24131. this._animationPropertiesOverride = value;
  24132. },
  24133. enumerable: true,
  24134. configurable: true
  24135. });
  24136. Object.defineProperty(Scene.prototype, "onDispose", {
  24137. /** Sets a function to be executed when this scene is disposed. */
  24138. set: function (callback) {
  24139. if (this._onDisposeObserver) {
  24140. this.onDisposeObservable.remove(this._onDisposeObserver);
  24141. }
  24142. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24143. },
  24144. enumerable: true,
  24145. configurable: true
  24146. });
  24147. Object.defineProperty(Scene.prototype, "beforeRender", {
  24148. /** Sets a function to be executed before rendering this scene */
  24149. set: function (callback) {
  24150. if (this._onBeforeRenderObserver) {
  24151. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24152. }
  24153. if (callback) {
  24154. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24155. }
  24156. },
  24157. enumerable: true,
  24158. configurable: true
  24159. });
  24160. Object.defineProperty(Scene.prototype, "afterRender", {
  24161. /** Sets a function to be executed after rendering this scene */
  24162. set: function (callback) {
  24163. if (this._onAfterRenderObserver) {
  24164. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24165. }
  24166. if (callback) {
  24167. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24168. }
  24169. },
  24170. enumerable: true,
  24171. configurable: true
  24172. });
  24173. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24174. /** Sets a function to be executed before rendering a camera*/
  24175. set: function (callback) {
  24176. if (this._onBeforeCameraRenderObserver) {
  24177. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24178. }
  24179. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24180. },
  24181. enumerable: true,
  24182. configurable: true
  24183. });
  24184. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24185. /** Sets a function to be executed after rendering a camera*/
  24186. set: function (callback) {
  24187. if (this._onAfterCameraRenderObserver) {
  24188. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24189. }
  24190. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24191. },
  24192. enumerable: true,
  24193. configurable: true
  24194. });
  24195. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24196. /**
  24197. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24198. */
  24199. get: function () {
  24200. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24201. },
  24202. enumerable: true,
  24203. configurable: true
  24204. });
  24205. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24206. get: function () {
  24207. return this._useRightHandedSystem;
  24208. },
  24209. /**
  24210. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24211. */
  24212. set: function (value) {
  24213. if (this._useRightHandedSystem === value) {
  24214. return;
  24215. }
  24216. this._useRightHandedSystem = value;
  24217. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24218. },
  24219. enumerable: true,
  24220. configurable: true
  24221. });
  24222. /**
  24223. * Sets the step Id used by deterministic lock step
  24224. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24225. * @param newStepId defines the step Id
  24226. */
  24227. Scene.prototype.setStepId = function (newStepId) {
  24228. this._currentStepId = newStepId;
  24229. };
  24230. ;
  24231. /**
  24232. * Gets the step Id used by deterministic lock step
  24233. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24234. * @returns the step Id
  24235. */
  24236. Scene.prototype.getStepId = function () {
  24237. return this._currentStepId;
  24238. };
  24239. ;
  24240. /**
  24241. * Gets the internal step used by deterministic lock step
  24242. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24243. * @returns the internal step
  24244. */
  24245. Scene.prototype.getInternalStep = function () {
  24246. return this._currentInternalStep;
  24247. };
  24248. ;
  24249. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24250. get: function () {
  24251. return this._fogEnabled;
  24252. },
  24253. /**
  24254. * Gets or sets a boolean indicating if fog is enabled on this scene
  24255. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24256. */
  24257. set: function (value) {
  24258. if (this._fogEnabled === value) {
  24259. return;
  24260. }
  24261. this._fogEnabled = value;
  24262. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24263. },
  24264. enumerable: true,
  24265. configurable: true
  24266. });
  24267. Object.defineProperty(Scene.prototype, "fogMode", {
  24268. get: function () {
  24269. return this._fogMode;
  24270. },
  24271. /**
  24272. * Gets or sets the fog mode to use
  24273. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24274. */
  24275. set: function (value) {
  24276. if (this._fogMode === value) {
  24277. return;
  24278. }
  24279. this._fogMode = value;
  24280. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24286. get: function () {
  24287. return this._shadowsEnabled;
  24288. },
  24289. /**
  24290. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24291. */
  24292. set: function (value) {
  24293. if (this._shadowsEnabled === value) {
  24294. return;
  24295. }
  24296. this._shadowsEnabled = value;
  24297. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24298. },
  24299. enumerable: true,
  24300. configurable: true
  24301. });
  24302. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24303. get: function () {
  24304. return this._lightsEnabled;
  24305. },
  24306. /**
  24307. * Gets or sets a boolean indicating if lights are enabled on this scene
  24308. */
  24309. set: function (value) {
  24310. if (this._lightsEnabled === value) {
  24311. return;
  24312. }
  24313. this._lightsEnabled = value;
  24314. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24315. },
  24316. enumerable: true,
  24317. configurable: true
  24318. });
  24319. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24320. /** The default material used on meshes when no material is affected */
  24321. get: function () {
  24322. if (!this._defaultMaterial) {
  24323. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24324. }
  24325. return this._defaultMaterial;
  24326. },
  24327. /** The default material used on meshes when no material is affected */
  24328. set: function (value) {
  24329. this._defaultMaterial = value;
  24330. },
  24331. enumerable: true,
  24332. configurable: true
  24333. });
  24334. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24335. get: function () {
  24336. return this._texturesEnabled;
  24337. },
  24338. /**
  24339. * Gets or sets a boolean indicating if textures are enabled on this scene
  24340. */
  24341. set: function (value) {
  24342. if (this._texturesEnabled === value) {
  24343. return;
  24344. }
  24345. this._texturesEnabled = value;
  24346. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24347. },
  24348. enumerable: true,
  24349. configurable: true
  24350. });
  24351. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24352. get: function () {
  24353. return this._skeletonsEnabled;
  24354. },
  24355. /**
  24356. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24357. */
  24358. set: function (value) {
  24359. if (this._skeletonsEnabled === value) {
  24360. return;
  24361. }
  24362. this._skeletonsEnabled = value;
  24363. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24364. },
  24365. enumerable: true,
  24366. configurable: true
  24367. });
  24368. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24369. /**
  24370. * Gets the postprocess render pipeline manager
  24371. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24372. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24373. */
  24374. get: function () {
  24375. if (!this._postProcessRenderPipelineManager) {
  24376. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24377. }
  24378. return this._postProcessRenderPipelineManager;
  24379. },
  24380. enumerable: true,
  24381. configurable: true
  24382. });
  24383. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24384. /**
  24385. * Gets the main soundtrack associated with the scene
  24386. */
  24387. get: function () {
  24388. if (!this._mainSoundTrack) {
  24389. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24390. }
  24391. return this._mainSoundTrack;
  24392. },
  24393. enumerable: true,
  24394. configurable: true
  24395. });
  24396. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24397. /** @hidden */
  24398. get: function () {
  24399. return this._alternateRendering;
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24405. /**
  24406. * Gets the list of frustum planes (built from the active camera)
  24407. */
  24408. get: function () {
  24409. return this._frustumPlanes;
  24410. },
  24411. enumerable: true,
  24412. configurable: true
  24413. });
  24414. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24415. /**
  24416. * Gets the current geometry buffer associated to the scene.
  24417. */
  24418. get: function () {
  24419. return this._geometryBufferRenderer;
  24420. },
  24421. /**
  24422. * Sets the current geometry buffer for the scene.
  24423. */
  24424. set: function (geometryBufferRenderer) {
  24425. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24426. this._geometryBufferRenderer = geometryBufferRenderer;
  24427. }
  24428. },
  24429. enumerable: true,
  24430. configurable: true
  24431. });
  24432. /**
  24433. * Registers the transient components if needed.
  24434. */
  24435. Scene.prototype._registerTransientComponents = function () {
  24436. // Register components that have been associated lately to the scene.
  24437. if (this._transientComponents.length > 0) {
  24438. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24439. var component = _a[_i];
  24440. component.register();
  24441. }
  24442. this._transientComponents = [];
  24443. }
  24444. };
  24445. /**
  24446. * Add a component to the scene.
  24447. * Note that the ccomponent could be registered on th next frame if this is called after
  24448. * the register component stage.
  24449. * @param component Defines the component to add to the scene
  24450. */
  24451. Scene.prototype._addComponent = function (component) {
  24452. this._components.push(component);
  24453. this._transientComponents.push(component);
  24454. var serializableComponent = component;
  24455. if (serializableComponent.addFromContainer) {
  24456. this._serializableComponents.push(serializableComponent);
  24457. }
  24458. };
  24459. /**
  24460. * Gets a component from the scene.
  24461. * @param name defines the name of the component to retrieve
  24462. * @returns the component or null if not present
  24463. */
  24464. Scene.prototype._getComponent = function (name) {
  24465. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24466. var component = _a[_i];
  24467. if (component.name === name) {
  24468. return component;
  24469. }
  24470. }
  24471. return null;
  24472. };
  24473. Object.defineProperty(Scene.prototype, "debugLayer", {
  24474. /**
  24475. * Gets the debug layer (aka Inspector) associated with the scene
  24476. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24477. */
  24478. get: function () {
  24479. if (!this._debugLayer) {
  24480. this._debugLayer = new BABYLON.DebugLayer(this);
  24481. }
  24482. return this._debugLayer;
  24483. },
  24484. enumerable: true,
  24485. configurable: true
  24486. });
  24487. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24488. /**
  24489. * Gets a boolean indicating if collisions are processed on a web worker
  24490. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24491. */
  24492. get: function () {
  24493. return this._workerCollisions;
  24494. },
  24495. set: function (enabled) {
  24496. if (!BABYLON.CollisionCoordinatorLegacy) {
  24497. return;
  24498. }
  24499. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24500. this._workerCollisions = enabled;
  24501. if (this.collisionCoordinator) {
  24502. this.collisionCoordinator.destroy();
  24503. }
  24504. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24505. this.collisionCoordinator.init(this);
  24506. },
  24507. enumerable: true,
  24508. configurable: true
  24509. });
  24510. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24511. /**
  24512. * Gets the octree used to boost mesh selection (picking)
  24513. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24514. */
  24515. get: function () {
  24516. return this._selectionOctree;
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24522. /**
  24523. * Gets the mesh that is currently under the pointer
  24524. */
  24525. get: function () {
  24526. return this._pointerOverMesh;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(Scene.prototype, "pointerX", {
  24532. /**
  24533. * Gets the current on-screen X position of the pointer
  24534. */
  24535. get: function () {
  24536. return this._pointerX;
  24537. },
  24538. enumerable: true,
  24539. configurable: true
  24540. });
  24541. Object.defineProperty(Scene.prototype, "pointerY", {
  24542. /**
  24543. * Gets the current on-screen Y position of the pointer
  24544. */
  24545. get: function () {
  24546. return this._pointerY;
  24547. },
  24548. enumerable: true,
  24549. configurable: true
  24550. });
  24551. /**
  24552. * Gets the cached material (ie. the latest rendered one)
  24553. * @returns the cached material
  24554. */
  24555. Scene.prototype.getCachedMaterial = function () {
  24556. return this._cachedMaterial;
  24557. };
  24558. /**
  24559. * Gets the cached effect (ie. the latest rendered one)
  24560. * @returns the cached effect
  24561. */
  24562. Scene.prototype.getCachedEffect = function () {
  24563. return this._cachedEffect;
  24564. };
  24565. /**
  24566. * Gets the cached visibility state (ie. the latest rendered one)
  24567. * @returns the cached visibility state
  24568. */
  24569. Scene.prototype.getCachedVisibility = function () {
  24570. return this._cachedVisibility;
  24571. };
  24572. /**
  24573. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24574. * @param material defines the current material
  24575. * @param effect defines the current effect
  24576. * @param visibility defines the current visibility state
  24577. * @returns true if one parameter is not cached
  24578. */
  24579. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24580. if (visibility === void 0) { visibility = 1; }
  24581. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24582. };
  24583. /**
  24584. * Gets the outline renderer associated with the scene
  24585. * @returns a OutlineRenderer
  24586. */
  24587. Scene.prototype.getOutlineRenderer = function () {
  24588. return this._outlineRenderer;
  24589. };
  24590. /**
  24591. * Gets the engine associated with the scene
  24592. * @returns an Engine
  24593. */
  24594. Scene.prototype.getEngine = function () {
  24595. return this._engine;
  24596. };
  24597. /**
  24598. * Gets the total number of vertices rendered per frame
  24599. * @returns the total number of vertices rendered per frame
  24600. */
  24601. Scene.prototype.getTotalVertices = function () {
  24602. return this._totalVertices.current;
  24603. };
  24604. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24605. /**
  24606. * Gets the performance counter for total vertices
  24607. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24608. */
  24609. get: function () {
  24610. return this._totalVertices;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. /**
  24616. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24617. * @returns the total number of active indices rendered per frame
  24618. */
  24619. Scene.prototype.getActiveIndices = function () {
  24620. return this._activeIndices.current;
  24621. };
  24622. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24623. /**
  24624. * Gets the performance counter for active indices
  24625. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24626. */
  24627. get: function () {
  24628. return this._activeIndices;
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. /**
  24634. * Gets the total number of active particles rendered per frame
  24635. * @returns the total number of active particles rendered per frame
  24636. */
  24637. Scene.prototype.getActiveParticles = function () {
  24638. return this._activeParticles.current;
  24639. };
  24640. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24641. /**
  24642. * Gets the performance counter for active particles
  24643. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24644. */
  24645. get: function () {
  24646. return this._activeParticles;
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. /**
  24652. * Gets the total number of active bones rendered per frame
  24653. * @returns the total number of active bones rendered per frame
  24654. */
  24655. Scene.prototype.getActiveBones = function () {
  24656. return this._activeBones.current;
  24657. };
  24658. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24659. /**
  24660. * Gets the performance counter for active bones
  24661. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24662. */
  24663. get: function () {
  24664. return this._activeBones;
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. /** @hidden */
  24670. Scene.prototype.getInterFramePerfCounter = function () {
  24671. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24672. return 0;
  24673. };
  24674. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24675. /** @hidden */
  24676. get: function () {
  24677. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24678. return null;
  24679. },
  24680. enumerable: true,
  24681. configurable: true
  24682. });
  24683. /** @hidden */
  24684. Scene.prototype.getLastFrameDuration = function () {
  24685. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24686. return 0;
  24687. };
  24688. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24689. /** @hidden */
  24690. get: function () {
  24691. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24692. return null;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. /** @hidden */
  24698. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24699. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24700. return 0;
  24701. };
  24702. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24703. /** @hidden */
  24704. get: function () {
  24705. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24706. return null;
  24707. },
  24708. enumerable: true,
  24709. configurable: true
  24710. });
  24711. /**
  24712. * Gets the array of active meshes
  24713. * @returns an array of AbstractMesh
  24714. */
  24715. Scene.prototype.getActiveMeshes = function () {
  24716. return this._activeMeshes;
  24717. };
  24718. /** @hidden */
  24719. Scene.prototype.getRenderTargetsDuration = function () {
  24720. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24721. return 0;
  24722. };
  24723. /** @hidden */
  24724. Scene.prototype.getRenderDuration = function () {
  24725. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24726. return 0;
  24727. };
  24728. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24729. /** @hidden */
  24730. get: function () {
  24731. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24732. return null;
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. /** @hidden */
  24738. Scene.prototype.getParticlesDuration = function () {
  24739. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24740. return 0;
  24741. };
  24742. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24743. /** @hidden */
  24744. get: function () {
  24745. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24746. return null;
  24747. },
  24748. enumerable: true,
  24749. configurable: true
  24750. });
  24751. /** @hidden */
  24752. Scene.prototype.getSpritesDuration = function () {
  24753. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24754. return 0;
  24755. };
  24756. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24757. /** @hidden */
  24758. get: function () {
  24759. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24760. return null;
  24761. },
  24762. enumerable: true,
  24763. configurable: true
  24764. });
  24765. /**
  24766. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24767. * @returns a number
  24768. */
  24769. Scene.prototype.getAnimationRatio = function () {
  24770. return this._animationRatio !== undefined ? this._animationRatio : 1;
  24771. };
  24772. /**
  24773. * Gets an unique Id for the current frame
  24774. * @returns a number
  24775. */
  24776. Scene.prototype.getRenderId = function () {
  24777. return this._renderId;
  24778. };
  24779. /** Call this function if you want to manually increment the render Id*/
  24780. Scene.prototype.incrementRenderId = function () {
  24781. this._renderId++;
  24782. };
  24783. Scene.prototype._updatePointerPosition = function (evt) {
  24784. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24785. if (!canvasRect) {
  24786. return;
  24787. }
  24788. this._pointerX = evt.clientX - canvasRect.left;
  24789. this._pointerY = evt.clientY - canvasRect.top;
  24790. this._unTranslatedPointerX = this._pointerX;
  24791. this._unTranslatedPointerY = this._pointerY;
  24792. };
  24793. Scene.prototype._createUbo = function () {
  24794. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24795. this._sceneUbo.addUniform("viewProjection", 16);
  24796. this._sceneUbo.addUniform("view", 16);
  24797. };
  24798. Scene.prototype._createAlternateUbo = function () {
  24799. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24800. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24801. this._alternateSceneUbo.addUniform("view", 16);
  24802. };
  24803. // Pointers handling
  24804. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24805. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24806. if (result) {
  24807. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24808. }
  24809. return result;
  24810. };
  24811. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24812. if (pointerInfo.pickInfo) {
  24813. if (!pointerInfo.pickInfo.ray) {
  24814. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24815. }
  24816. }
  24817. };
  24818. /**
  24819. * Use this method to simulate a pointer move on a mesh
  24820. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24821. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24822. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24823. * @returns the current scene
  24824. */
  24825. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24826. var evt = new PointerEvent("pointermove", pointerEventInit);
  24827. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24828. return this;
  24829. }
  24830. return this._processPointerMove(pickResult, evt);
  24831. };
  24832. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24833. var canvas = this._engine.getRenderingCanvas();
  24834. if (!canvas) {
  24835. return this;
  24836. }
  24837. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24838. this.setPointerOverSprite(null);
  24839. this.setPointerOverMesh(pickResult.pickedMesh);
  24840. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24841. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24842. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24843. }
  24844. else {
  24845. canvas.style.cursor = this.hoverCursor;
  24846. }
  24847. }
  24848. else {
  24849. canvas.style.cursor = this.defaultCursor;
  24850. }
  24851. }
  24852. else {
  24853. this.setPointerOverMesh(null);
  24854. // Sprites
  24855. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24856. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24857. this.setPointerOverSprite(pickResult.pickedSprite);
  24858. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24859. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24860. }
  24861. else {
  24862. canvas.style.cursor = this.hoverCursor;
  24863. }
  24864. }
  24865. else {
  24866. this.setPointerOverSprite(null);
  24867. // Restore pointer
  24868. canvas.style.cursor = this.defaultCursor;
  24869. }
  24870. }
  24871. if (pickResult) {
  24872. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24873. if (this.onPointerMove) {
  24874. this.onPointerMove(evt, pickResult, type);
  24875. }
  24876. if (this.onPointerObservable.hasObservers()) {
  24877. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24878. this._setRayOnPointerInfo(pi);
  24879. this.onPointerObservable.notifyObservers(pi, type);
  24880. }
  24881. }
  24882. return this;
  24883. };
  24884. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  24885. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  24886. if (pickResult) {
  24887. pi.ray = pickResult.ray;
  24888. }
  24889. this.onPrePointerObservable.notifyObservers(pi, type);
  24890. if (pi.skipOnPointerObservable) {
  24891. return true;
  24892. }
  24893. else {
  24894. return false;
  24895. }
  24896. };
  24897. /**
  24898. * Use this method to simulate a pointer down on a mesh
  24899. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24900. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24901. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24902. * @returns the current scene
  24903. */
  24904. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24905. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24906. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  24907. return this;
  24908. }
  24909. return this._processPointerDown(pickResult, evt);
  24910. };
  24911. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24912. var _this = this;
  24913. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24914. this._pickedDownMesh = pickResult.pickedMesh;
  24915. var actionManager = pickResult.pickedMesh.actionManager;
  24916. if (actionManager) {
  24917. if (actionManager.hasPickTriggers) {
  24918. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24919. switch (evt.button) {
  24920. case 0:
  24921. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24922. break;
  24923. case 1:
  24924. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24925. break;
  24926. case 2:
  24927. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24928. break;
  24929. }
  24930. }
  24931. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24932. window.setTimeout(function () {
  24933. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
  24934. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24935. if (_this._totalPointersPressed !== 0 &&
  24936. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24937. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24938. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24939. _this._startingPointerTime = 0;
  24940. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24941. }
  24942. }
  24943. }, Scene.LongPressDelay);
  24944. }
  24945. }
  24946. }
  24947. if (pickResult) {
  24948. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24949. if (this.onPointerDown) {
  24950. this.onPointerDown(evt, pickResult, type);
  24951. }
  24952. if (this.onPointerObservable.hasObservers()) {
  24953. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24954. this._setRayOnPointerInfo(pi);
  24955. this.onPointerObservable.notifyObservers(pi, type);
  24956. }
  24957. }
  24958. return this;
  24959. };
  24960. /**
  24961. * Use this method to simulate a pointer up on a mesh
  24962. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24963. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24964. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24965. * @returns the current scene
  24966. */
  24967. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24968. var evt = new PointerEvent("pointerup", pointerEventInit);
  24969. var clickInfo = new ClickInfo();
  24970. clickInfo.singleClick = true;
  24971. clickInfo.ignore = true;
  24972. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  24973. return this;
  24974. }
  24975. return this._processPointerUp(pickResult, evt, clickInfo);
  24976. };
  24977. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24978. if (pickResult && pickResult && pickResult.pickedMesh) {
  24979. this._pickedUpMesh = pickResult.pickedMesh;
  24980. if (this._pickedDownMesh === this._pickedUpMesh) {
  24981. if (this.onPointerPick) {
  24982. this.onPointerPick(evt, pickResult);
  24983. }
  24984. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24985. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24986. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24987. this._setRayOnPointerInfo(pi);
  24988. this.onPointerObservable.notifyObservers(pi, type_1);
  24989. }
  24990. }
  24991. if (pickResult.pickedMesh.actionManager) {
  24992. if (clickInfo.ignore) {
  24993. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24994. }
  24995. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24996. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24997. }
  24998. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24999. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25000. }
  25001. }
  25002. }
  25003. if (this._pickedDownMesh &&
  25004. this._pickedDownMesh.actionManager &&
  25005. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25006. this._pickedDownMesh !== this._pickedUpMesh) {
  25007. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25008. }
  25009. var type = BABYLON.PointerEventTypes.POINTERUP;
  25010. if (this.onPointerObservable.hasObservers()) {
  25011. if (!clickInfo.ignore) {
  25012. if (!clickInfo.hasSwiped) {
  25013. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25014. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25015. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25016. this._setRayOnPointerInfo(pi);
  25017. this.onPointerObservable.notifyObservers(pi, type_2);
  25018. }
  25019. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25020. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25021. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25022. this._setRayOnPointerInfo(pi);
  25023. this.onPointerObservable.notifyObservers(pi, type_3);
  25024. }
  25025. }
  25026. }
  25027. else {
  25028. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25029. this._setRayOnPointerInfo(pi);
  25030. this.onPointerObservable.notifyObservers(pi, type);
  25031. }
  25032. }
  25033. if (this.onPointerUp) {
  25034. this.onPointerUp(evt, pickResult, type);
  25035. }
  25036. return this;
  25037. };
  25038. /**
  25039. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25040. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25041. * @returns true if the pointer was captured
  25042. */
  25043. Scene.prototype.isPointerCaptured = function (pointerId) {
  25044. if (pointerId === void 0) { pointerId = 0; }
  25045. return this._pointerCaptures[pointerId];
  25046. };
  25047. /**
  25048. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25049. * @param attachUp defines if you want to attach events to pointerup
  25050. * @param attachDown defines if you want to attach events to pointerdown
  25051. * @param attachMove defines if you want to attach events to pointermove
  25052. */
  25053. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25054. var _this = this;
  25055. if (attachUp === void 0) { attachUp = true; }
  25056. if (attachDown === void 0) { attachDown = true; }
  25057. if (attachMove === void 0) { attachMove = true; }
  25058. this._initActionManager = function (act, clickInfo) {
  25059. if (!_this._meshPickProceed) {
  25060. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25061. _this._currentPickResult = pickResult;
  25062. if (pickResult) {
  25063. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25064. }
  25065. _this._meshPickProceed = true;
  25066. }
  25067. return act;
  25068. };
  25069. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25070. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25071. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25072. btn !== _this._previousButtonPressed) {
  25073. _this._doubleClickOccured = false;
  25074. clickInfo.singleClick = true;
  25075. clickInfo.ignore = false;
  25076. cb(clickInfo, _this._currentPickResult);
  25077. }
  25078. };
  25079. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25080. var clickInfo = new ClickInfo();
  25081. _this._currentPickResult = null;
  25082. var act = null;
  25083. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25084. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25085. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25086. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25087. act = _this._initActionManager(act, clickInfo);
  25088. if (act)
  25089. checkPicking = act.hasPickTriggers;
  25090. }
  25091. if (checkPicking) {
  25092. var btn = evt.button;
  25093. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25094. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25095. if (!clickInfo.hasSwiped) {
  25096. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25097. if (!checkSingleClickImmediately) {
  25098. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25099. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25100. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25101. act = _this._initActionManager(act, clickInfo);
  25102. if (act)
  25103. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25104. }
  25105. }
  25106. if (checkSingleClickImmediately) {
  25107. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25108. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25109. btn !== _this._previousButtonPressed) {
  25110. clickInfo.singleClick = true;
  25111. cb(clickInfo, _this._currentPickResult);
  25112. }
  25113. }
  25114. // at least one double click is required to be check and exclusive double click is enabled
  25115. else {
  25116. // wait that no double click has been raised during the double click delay
  25117. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25118. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25119. }
  25120. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25121. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25122. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25123. act = _this._initActionManager(act, clickInfo);
  25124. if (act)
  25125. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25126. }
  25127. if (checkDoubleClick) {
  25128. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25129. if (btn === _this._previousButtonPressed &&
  25130. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25131. !_this._doubleClickOccured) {
  25132. // pointer has not moved for 2 clicks, it's a double click
  25133. if (!clickInfo.hasSwiped &&
  25134. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25135. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25136. _this._previousStartingPointerTime = 0;
  25137. _this._doubleClickOccured = true;
  25138. clickInfo.doubleClick = true;
  25139. clickInfo.ignore = false;
  25140. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25141. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25142. }
  25143. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25144. cb(clickInfo, _this._currentPickResult);
  25145. }
  25146. // if the two successive clicks are too far, it's just two simple clicks
  25147. else {
  25148. _this._doubleClickOccured = false;
  25149. _this._previousStartingPointerTime = _this._startingPointerTime;
  25150. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25151. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25152. _this._previousButtonPressed = btn;
  25153. if (Scene.ExclusiveDoubleClickMode) {
  25154. if (_this._previousDelayedSimpleClickTimeout) {
  25155. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25156. }
  25157. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25158. cb(clickInfo, _this._previousPickResult);
  25159. }
  25160. else {
  25161. cb(clickInfo, _this._currentPickResult);
  25162. }
  25163. }
  25164. }
  25165. // just the first click of the double has been raised
  25166. else {
  25167. _this._doubleClickOccured = false;
  25168. _this._previousStartingPointerTime = _this._startingPointerTime;
  25169. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25170. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25171. _this._previousButtonPressed = btn;
  25172. }
  25173. }
  25174. }
  25175. }
  25176. clickInfo.ignore = true;
  25177. cb(clickInfo, _this._currentPickResult);
  25178. };
  25179. this._spritePredicate = function (sprite) {
  25180. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25181. };
  25182. this._onPointerMove = function (evt) {
  25183. _this._updatePointerPosition(evt);
  25184. // PreObservable support
  25185. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25186. return;
  25187. }
  25188. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25189. return;
  25190. }
  25191. if (!_this.pointerMovePredicate) {
  25192. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25193. }
  25194. // Meshes
  25195. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25196. _this._processPointerMove(pickResult, evt);
  25197. };
  25198. this._onPointerDown = function (evt) {
  25199. _this._totalPointersPressed++;
  25200. _this._pickedDownMesh = null;
  25201. _this._meshPickProceed = false;
  25202. _this._updatePointerPosition(evt);
  25203. if (_this.preventDefaultOnPointerDown && canvas) {
  25204. evt.preventDefault();
  25205. canvas.focus();
  25206. }
  25207. // PreObservable support
  25208. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25209. return;
  25210. }
  25211. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25212. return;
  25213. }
  25214. _this._pointerCaptures[evt.pointerId] = true;
  25215. _this._startingPointerPosition.x = _this._pointerX;
  25216. _this._startingPointerPosition.y = _this._pointerY;
  25217. _this._startingPointerTime = Date.now();
  25218. if (!_this.pointerDownPredicate) {
  25219. _this.pointerDownPredicate = function (mesh) {
  25220. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25221. };
  25222. }
  25223. // Meshes
  25224. _this._pickedDownMesh = null;
  25225. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25226. _this._processPointerDown(pickResult, evt);
  25227. // Sprites
  25228. _this._pickedDownSprite = null;
  25229. if (_this.spriteManagers.length > 0) {
  25230. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25231. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25232. if (pickResult.pickedSprite.actionManager) {
  25233. _this._pickedDownSprite = pickResult.pickedSprite;
  25234. switch (evt.button) {
  25235. case 0:
  25236. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25237. break;
  25238. case 1:
  25239. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25240. break;
  25241. case 2:
  25242. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25243. break;
  25244. }
  25245. if (pickResult.pickedSprite.actionManager) {
  25246. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25247. }
  25248. }
  25249. }
  25250. }
  25251. };
  25252. this._onPointerUp = function (evt) {
  25253. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25254. return; // So we need to test it the pointer down was pressed before.
  25255. }
  25256. _this._totalPointersPressed--;
  25257. _this._pickedUpMesh = null;
  25258. _this._meshPickProceed = false;
  25259. _this._updatePointerPosition(evt);
  25260. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25261. // PreObservable support
  25262. if (_this.onPrePointerObservable.hasObservers()) {
  25263. if (!clickInfo.ignore) {
  25264. if (!clickInfo.hasSwiped) {
  25265. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25266. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25267. return;
  25268. }
  25269. }
  25270. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25271. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25272. return;
  25273. }
  25274. }
  25275. }
  25276. }
  25277. else {
  25278. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25279. return;
  25280. }
  25281. }
  25282. }
  25283. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25284. return;
  25285. }
  25286. _this._pointerCaptures[evt.pointerId] = false;
  25287. if (!_this.pointerUpPredicate) {
  25288. _this.pointerUpPredicate = function (mesh) {
  25289. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25290. };
  25291. }
  25292. // Meshes
  25293. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25294. _this._initActionManager(null, clickInfo);
  25295. }
  25296. if (!pickResult) {
  25297. pickResult = _this._currentPickResult;
  25298. }
  25299. _this._processPointerUp(pickResult, evt, clickInfo);
  25300. // Sprites
  25301. if (!clickInfo.ignore) {
  25302. if (_this.spriteManagers.length > 0) {
  25303. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25304. if (spritePickResult) {
  25305. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25306. if (spritePickResult.pickedSprite.actionManager) {
  25307. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25308. if (spritePickResult.pickedSprite.actionManager) {
  25309. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25310. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25311. }
  25312. }
  25313. }
  25314. }
  25315. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25316. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25317. }
  25318. }
  25319. }
  25320. }
  25321. _this._previousPickResult = _this._currentPickResult;
  25322. });
  25323. };
  25324. this._onKeyDown = function (evt) {
  25325. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25326. if (_this.onPreKeyboardObservable.hasObservers()) {
  25327. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25328. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25329. if (pi.skipOnPointerObservable) {
  25330. return;
  25331. }
  25332. }
  25333. if (_this.onKeyboardObservable.hasObservers()) {
  25334. var pi = new BABYLON.KeyboardInfo(type, evt);
  25335. _this.onKeyboardObservable.notifyObservers(pi, type);
  25336. }
  25337. if (_this.actionManager) {
  25338. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25339. }
  25340. };
  25341. this._onKeyUp = function (evt) {
  25342. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25343. if (_this.onPreKeyboardObservable.hasObservers()) {
  25344. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25345. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25346. if (pi.skipOnPointerObservable) {
  25347. return;
  25348. }
  25349. }
  25350. if (_this.onKeyboardObservable.hasObservers()) {
  25351. var pi = new BABYLON.KeyboardInfo(type, evt);
  25352. _this.onKeyboardObservable.notifyObservers(pi, type);
  25353. }
  25354. if (_this.actionManager) {
  25355. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25356. }
  25357. };
  25358. var engine = this.getEngine();
  25359. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25360. if (!canvas) {
  25361. return;
  25362. }
  25363. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25364. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25365. });
  25366. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25367. if (!canvas) {
  25368. return;
  25369. }
  25370. canvas.removeEventListener("keydown", _this._onKeyDown);
  25371. canvas.removeEventListener("keyup", _this._onKeyUp);
  25372. });
  25373. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25374. var canvas = this._engine.getRenderingCanvas();
  25375. if (!canvas) {
  25376. return;
  25377. }
  25378. if (attachMove) {
  25379. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25380. // Wheel
  25381. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25382. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25383. }
  25384. if (attachDown) {
  25385. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25386. }
  25387. if (attachUp) {
  25388. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25389. }
  25390. canvas.tabIndex = 1;
  25391. };
  25392. /** Detaches all event handlers*/
  25393. Scene.prototype.detachControl = function () {
  25394. var engine = this.getEngine();
  25395. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25396. var canvas = engine.getRenderingCanvas();
  25397. if (!canvas) {
  25398. return;
  25399. }
  25400. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25401. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25402. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25403. if (this._onCanvasBlurObserver) {
  25404. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25405. }
  25406. if (this._onCanvasFocusObserver) {
  25407. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25408. }
  25409. // Wheel
  25410. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25411. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25412. // Keyboard
  25413. canvas.removeEventListener("keydown", this._onKeyDown);
  25414. canvas.removeEventListener("keyup", this._onKeyUp);
  25415. // Observables
  25416. this.onKeyboardObservable.clear();
  25417. this.onPreKeyboardObservable.clear();
  25418. this.onPointerObservable.clear();
  25419. this.onPrePointerObservable.clear();
  25420. };
  25421. /**
  25422. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25423. * Delay loaded resources are not taking in account
  25424. * @return true if all required resources are ready
  25425. */
  25426. Scene.prototype.isReady = function () {
  25427. if (this._isDisposed) {
  25428. return false;
  25429. }
  25430. if (this._pendingData.length > 0) {
  25431. return false;
  25432. }
  25433. var index;
  25434. var engine = this.getEngine();
  25435. // Geometries
  25436. for (index = 0; index < this.geometries.length; index++) {
  25437. var geometry = this.geometries[index];
  25438. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25439. return false;
  25440. }
  25441. }
  25442. // Meshes
  25443. for (index = 0; index < this.meshes.length; index++) {
  25444. var mesh = this.meshes[index];
  25445. if (!mesh.isEnabled()) {
  25446. continue;
  25447. }
  25448. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25449. continue;
  25450. }
  25451. if (!mesh.isReady(true)) {
  25452. return false;
  25453. }
  25454. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25455. // Is Ready For Mesh
  25456. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25457. var step = _a[_i];
  25458. if (!step.action(mesh, hardwareInstancedRendering)) {
  25459. return false;
  25460. }
  25461. }
  25462. }
  25463. // Post-processes
  25464. if (this.activeCameras && this.activeCameras.length > 0) {
  25465. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25466. var camera = _c[_b];
  25467. if (!camera.isReady(true)) {
  25468. return false;
  25469. }
  25470. }
  25471. }
  25472. else if (this.activeCamera) {
  25473. if (!this.activeCamera.isReady(true)) {
  25474. return false;
  25475. }
  25476. }
  25477. // Particles
  25478. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25479. var particleSystem = _e[_d];
  25480. if (!particleSystem.isReady()) {
  25481. return false;
  25482. }
  25483. }
  25484. return true;
  25485. };
  25486. /** Resets all cached information relative to material (including effect and visibility) */
  25487. Scene.prototype.resetCachedMaterial = function () {
  25488. this._cachedMaterial = null;
  25489. this._cachedEffect = null;
  25490. this._cachedVisibility = null;
  25491. };
  25492. /**
  25493. * Registers a function to be called before every frame render
  25494. * @param func defines the function to register
  25495. */
  25496. Scene.prototype.registerBeforeRender = function (func) {
  25497. this.onBeforeRenderObservable.add(func);
  25498. };
  25499. /**
  25500. * Unregisters a function called before every frame render
  25501. * @param func defines the function to unregister
  25502. */
  25503. Scene.prototype.unregisterBeforeRender = function (func) {
  25504. this.onBeforeRenderObservable.removeCallback(func);
  25505. };
  25506. /**
  25507. * Registers a function to be called after every frame render
  25508. * @param func defines the function to register
  25509. */
  25510. Scene.prototype.registerAfterRender = function (func) {
  25511. this.onAfterRenderObservable.add(func);
  25512. };
  25513. /**
  25514. * Unregisters a function called after every frame render
  25515. * @param func defines the function to unregister
  25516. */
  25517. Scene.prototype.unregisterAfterRender = function (func) {
  25518. this.onAfterRenderObservable.removeCallback(func);
  25519. };
  25520. Scene.prototype._executeOnceBeforeRender = function (func) {
  25521. var _this = this;
  25522. var execFunc = function () {
  25523. func();
  25524. setTimeout(function () {
  25525. _this.unregisterBeforeRender(execFunc);
  25526. });
  25527. };
  25528. this.registerBeforeRender(execFunc);
  25529. };
  25530. /**
  25531. * The provided function will run before render once and will be disposed afterwards.
  25532. * A timeout delay can be provided so that the function will be executed in N ms.
  25533. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25534. * @param func The function to be executed.
  25535. * @param timeout optional delay in ms
  25536. */
  25537. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25538. var _this = this;
  25539. if (timeout !== undefined) {
  25540. setTimeout(function () {
  25541. _this._executeOnceBeforeRender(func);
  25542. }, timeout);
  25543. }
  25544. else {
  25545. this._executeOnceBeforeRender(func);
  25546. }
  25547. };
  25548. /** @hidden */
  25549. Scene.prototype._addPendingData = function (data) {
  25550. this._pendingData.push(data);
  25551. };
  25552. /** @hidden */
  25553. Scene.prototype._removePendingData = function (data) {
  25554. var wasLoading = this.isLoading;
  25555. var index = this._pendingData.indexOf(data);
  25556. if (index !== -1) {
  25557. this._pendingData.splice(index, 1);
  25558. }
  25559. if (wasLoading && !this.isLoading) {
  25560. this.onDataLoadedObservable.notifyObservers(this);
  25561. }
  25562. };
  25563. /**
  25564. * Returns the number of items waiting to be loaded
  25565. * @returns the number of items waiting to be loaded
  25566. */
  25567. Scene.prototype.getWaitingItemsCount = function () {
  25568. return this._pendingData.length;
  25569. };
  25570. Object.defineProperty(Scene.prototype, "isLoading", {
  25571. /**
  25572. * Returns a boolean indicating if the scene is still loading data
  25573. */
  25574. get: function () {
  25575. return this._pendingData.length > 0;
  25576. },
  25577. enumerable: true,
  25578. configurable: true
  25579. });
  25580. /**
  25581. * Registers a function to be executed when the scene is ready
  25582. * @param {Function} func - the function to be executed
  25583. */
  25584. Scene.prototype.executeWhenReady = function (func) {
  25585. var _this = this;
  25586. this.onReadyObservable.add(func);
  25587. if (this._executeWhenReadyTimeoutId !== -1) {
  25588. return;
  25589. }
  25590. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25591. _this._checkIsReady();
  25592. }, 150);
  25593. };
  25594. /**
  25595. * Returns a promise that resolves when the scene is ready
  25596. * @returns A promise that resolves when the scene is ready
  25597. */
  25598. Scene.prototype.whenReadyAsync = function () {
  25599. var _this = this;
  25600. return new Promise(function (resolve) {
  25601. _this.executeWhenReady(function () {
  25602. resolve();
  25603. });
  25604. });
  25605. };
  25606. /** @hidden */
  25607. Scene.prototype._checkIsReady = function () {
  25608. var _this = this;
  25609. this._registerTransientComponents();
  25610. if (this.isReady()) {
  25611. this.onReadyObservable.notifyObservers(this);
  25612. this.onReadyObservable.clear();
  25613. this._executeWhenReadyTimeoutId = -1;
  25614. return;
  25615. }
  25616. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25617. _this._checkIsReady();
  25618. }, 150);
  25619. };
  25620. // Animations
  25621. /**
  25622. * Will start the animation sequence of a given target
  25623. * @param target defines the target
  25624. * @param from defines from which frame should animation start
  25625. * @param to defines until which frame should animation run.
  25626. * @param weight defines the weight to apply to the animation (1.0 by default)
  25627. * @param loop defines if the animation loops
  25628. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25629. * @param onAnimationEnd defines the function to be executed when the animation ends
  25630. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25631. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25632. * @returns the animatable object created for this animation
  25633. */
  25634. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25635. if (weight === void 0) { weight = 1.0; }
  25636. if (speedRatio === void 0) { speedRatio = 1.0; }
  25637. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25638. returnedAnimatable.weight = weight;
  25639. return returnedAnimatable;
  25640. };
  25641. /**
  25642. * Will start the animation sequence of a given target
  25643. * @param target defines the target
  25644. * @param from defines from which frame should animation start
  25645. * @param to defines until which frame should animation run.
  25646. * @param loop defines if the animation loops
  25647. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25648. * @param onAnimationEnd defines the function to be executed when the animation ends
  25649. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25650. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25651. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25652. * @returns the animatable object created for this animation
  25653. */
  25654. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25655. if (speedRatio === void 0) { speedRatio = 1.0; }
  25656. if (stopCurrent === void 0) { stopCurrent = true; }
  25657. if (from > to && speedRatio > 0) {
  25658. speedRatio *= -1;
  25659. }
  25660. if (stopCurrent) {
  25661. this.stopAnimation(target, undefined, targetMask);
  25662. }
  25663. if (!animatable) {
  25664. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25665. }
  25666. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25667. // Local animations
  25668. if (target.animations && shouldRunTargetAnimations) {
  25669. animatable.appendAnimations(target, target.animations);
  25670. }
  25671. // Children animations
  25672. if (target.getAnimatables) {
  25673. var animatables = target.getAnimatables();
  25674. for (var index = 0; index < animatables.length; index++) {
  25675. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25676. }
  25677. }
  25678. animatable.reset();
  25679. return animatable;
  25680. };
  25681. /**
  25682. * Begin a new animation on a given node
  25683. * @param target defines the target where the animation will take place
  25684. * @param animations defines the list of animations to start
  25685. * @param from defines the initial value
  25686. * @param to defines the final value
  25687. * @param loop defines if you want animation to loop (off by default)
  25688. * @param speedRatio defines the speed ratio to apply to all animations
  25689. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25690. * @returns the list of created animatables
  25691. */
  25692. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25693. if (speedRatio === undefined) {
  25694. speedRatio = 1.0;
  25695. }
  25696. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25697. return animatable;
  25698. };
  25699. /**
  25700. * Begin a new animation on a given node and its hierarchy
  25701. * @param target defines the root node where the animation will take place
  25702. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25703. * @param animations defines the list of animations to start
  25704. * @param from defines the initial value
  25705. * @param to defines the final value
  25706. * @param loop defines if you want animation to loop (off by default)
  25707. * @param speedRatio defines the speed ratio to apply to all animations
  25708. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25709. * @returns the list of animatables created for all nodes
  25710. */
  25711. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25712. var children = target.getDescendants(directDescendantsOnly);
  25713. var result = [];
  25714. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25715. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25716. var child = children_1[_i];
  25717. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25718. }
  25719. return result;
  25720. };
  25721. /**
  25722. * Gets the animatable associated with a specific target
  25723. * @param target defines the target of the animatable
  25724. * @returns the required animatable if found
  25725. */
  25726. Scene.prototype.getAnimatableByTarget = function (target) {
  25727. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25728. if (this._activeAnimatables[index].target === target) {
  25729. return this._activeAnimatables[index];
  25730. }
  25731. }
  25732. return null;
  25733. };
  25734. /**
  25735. * Gets all animatables associated with a given target
  25736. * @param target defines the target to look animatables for
  25737. * @returns an array of Animatables
  25738. */
  25739. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25740. var result = [];
  25741. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25742. if (this._activeAnimatables[index].target === target) {
  25743. result.push(this._activeAnimatables[index]);
  25744. }
  25745. }
  25746. return result;
  25747. };
  25748. Object.defineProperty(Scene.prototype, "animatables", {
  25749. /**
  25750. * Gets all animatable attached to the scene
  25751. */
  25752. get: function () {
  25753. return this._activeAnimatables;
  25754. },
  25755. enumerable: true,
  25756. configurable: true
  25757. });
  25758. /**
  25759. * Will stop the animation of the given target
  25760. * @param target - the target
  25761. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25762. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  25763. */
  25764. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25765. var animatables = this.getAllAnimatablesByTarget(target);
  25766. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25767. var animatable = animatables_1[_i];
  25768. animatable.stop(animationName, targetMask);
  25769. }
  25770. };
  25771. /**
  25772. * Stops and removes all animations that have been applied to the scene
  25773. */
  25774. Scene.prototype.stopAllAnimations = function () {
  25775. if (this._activeAnimatables) {
  25776. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25777. this._activeAnimatables[i].stop();
  25778. }
  25779. this._activeAnimatables = [];
  25780. }
  25781. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25782. var group = _a[_i];
  25783. group.stop();
  25784. }
  25785. };
  25786. Scene.prototype._animate = function () {
  25787. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25788. return;
  25789. }
  25790. // Getting time
  25791. var now = BABYLON.Tools.Now;
  25792. if (!this._animationTimeLast) {
  25793. if (this._pendingData.length > 0) {
  25794. return;
  25795. }
  25796. this._animationTimeLast = now;
  25797. }
  25798. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25799. this._animationTime += deltaTime;
  25800. this._animationTimeLast = now;
  25801. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25802. this._activeAnimatables[index]._animate(this._animationTime);
  25803. }
  25804. // Late animation bindings
  25805. this._processLateAnimationBindings();
  25806. };
  25807. /** @hidden */
  25808. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25809. var target = runtimeAnimation.target;
  25810. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25811. if (!target._lateAnimationHolders) {
  25812. target._lateAnimationHolders = {};
  25813. }
  25814. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25815. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25816. totalWeight: 0,
  25817. animations: [],
  25818. originalValue: originalValue
  25819. };
  25820. }
  25821. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25822. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25823. };
  25824. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25825. var normalizer = 1.0;
  25826. var finalPosition = BABYLON.Tmp.Vector3[0];
  25827. var finalScaling = BABYLON.Tmp.Vector3[1];
  25828. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25829. var startIndex = 0;
  25830. var originalAnimation = holder.animations[0];
  25831. var originalValue = holder.originalValue;
  25832. var scale = 1;
  25833. if (holder.totalWeight < 1.0) {
  25834. // We need to mix the original value in
  25835. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25836. scale = 1.0 - holder.totalWeight;
  25837. }
  25838. else {
  25839. startIndex = 1;
  25840. // We need to normalize the weights
  25841. normalizer = holder.totalWeight;
  25842. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25843. scale = originalAnimation.weight / normalizer;
  25844. if (scale == 1) {
  25845. return originalAnimation.currentValue;
  25846. }
  25847. }
  25848. finalScaling.scaleInPlace(scale);
  25849. finalPosition.scaleInPlace(scale);
  25850. finalQuaternion.scaleInPlace(scale);
  25851. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25852. var runtimeAnimation = holder.animations[animIndex];
  25853. var scale = runtimeAnimation.weight / normalizer;
  25854. var currentPosition = BABYLON.Tmp.Vector3[2];
  25855. var currentScaling = BABYLON.Tmp.Vector3[3];
  25856. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25857. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25858. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25859. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25860. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25861. }
  25862. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25863. return originalAnimation._workValue;
  25864. };
  25865. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25866. var originalAnimation = holder.animations[0];
  25867. var originalValue = holder.originalValue;
  25868. if (holder.animations.length === 1) {
  25869. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25870. }
  25871. var normalizer = 1.0;
  25872. var quaternions;
  25873. var weights;
  25874. if (holder.totalWeight < 1.0) {
  25875. var scale = 1.0 - holder.totalWeight;
  25876. quaternions = [];
  25877. weights = [];
  25878. quaternions.push(originalValue);
  25879. weights.push(scale);
  25880. }
  25881. else {
  25882. if (holder.animations.length === 2) { // Slerp as soon as we can
  25883. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25884. }
  25885. quaternions = [];
  25886. weights = [];
  25887. normalizer = holder.totalWeight;
  25888. }
  25889. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25890. var runtimeAnimation = holder.animations[animIndex];
  25891. quaternions.push(runtimeAnimation.currentValue);
  25892. weights.push(runtimeAnimation.weight / normalizer);
  25893. }
  25894. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25895. var cumulativeAmount = 0;
  25896. var cumulativeQuaternion = null;
  25897. for (var index = 0; index < quaternions.length;) {
  25898. if (!cumulativeQuaternion) {
  25899. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25900. cumulativeAmount = weights[index] + weights[index + 1];
  25901. index += 2;
  25902. continue;
  25903. }
  25904. cumulativeAmount += weights[index];
  25905. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25906. index++;
  25907. }
  25908. return cumulativeQuaternion;
  25909. };
  25910. Scene.prototype._processLateAnimationBindings = function () {
  25911. if (!this._registeredForLateAnimationBindings.length) {
  25912. return;
  25913. }
  25914. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25915. var target = this._registeredForLateAnimationBindings.data[index];
  25916. for (var path in target._lateAnimationHolders) {
  25917. var holder = target._lateAnimationHolders[path];
  25918. var originalAnimation = holder.animations[0];
  25919. var originalValue = holder.originalValue;
  25920. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25921. var finalValue = void 0;
  25922. if (matrixDecomposeMode) {
  25923. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25924. }
  25925. else {
  25926. var quaternionMode = originalValue.w !== undefined;
  25927. if (quaternionMode) {
  25928. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25929. }
  25930. else {
  25931. var startIndex = 0;
  25932. var normalizer = 1.0;
  25933. if (holder.totalWeight < 1.0) {
  25934. // We need to mix the original value in
  25935. if (originalValue.scale) {
  25936. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25937. }
  25938. else {
  25939. finalValue = originalValue * (1.0 - holder.totalWeight);
  25940. }
  25941. }
  25942. else {
  25943. // We need to normalize the weights
  25944. normalizer = holder.totalWeight;
  25945. var scale_1 = originalAnimation.weight / normalizer;
  25946. if (scale_1 !== 1) {
  25947. if (originalAnimation.currentValue.scale) {
  25948. finalValue = originalAnimation.currentValue.scale(scale_1);
  25949. }
  25950. else {
  25951. finalValue = originalAnimation.currentValue * scale_1;
  25952. }
  25953. }
  25954. else {
  25955. finalValue = originalAnimation.currentValue;
  25956. }
  25957. startIndex = 1;
  25958. }
  25959. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25960. var runtimeAnimation = holder.animations[animIndex];
  25961. var scale = runtimeAnimation.weight / normalizer;
  25962. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25963. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25964. }
  25965. else {
  25966. finalValue += runtimeAnimation.currentValue * scale;
  25967. }
  25968. }
  25969. }
  25970. }
  25971. target[path] = finalValue;
  25972. }
  25973. target._lateAnimationHolders = {};
  25974. }
  25975. this._registeredForLateAnimationBindings.reset();
  25976. };
  25977. // Matrix
  25978. /** @hidden */
  25979. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25980. this._useAlternateCameraConfiguration = active;
  25981. };
  25982. /**
  25983. * Gets the current view matrix
  25984. * @returns a Matrix
  25985. */
  25986. Scene.prototype.getViewMatrix = function () {
  25987. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25988. };
  25989. /**
  25990. * Gets the current projection matrix
  25991. * @returns a Matrix
  25992. */
  25993. Scene.prototype.getProjectionMatrix = function () {
  25994. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25995. };
  25996. /**
  25997. * Gets the current transform matrix
  25998. * @returns a Matrix made of View * Projection
  25999. */
  26000. Scene.prototype.getTransformMatrix = function () {
  26001. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26002. };
  26003. /**
  26004. * Sets the current transform matrix
  26005. * @param view defines the View matrix to use
  26006. * @param projection defines the Projection matrix to use
  26007. */
  26008. Scene.prototype.setTransformMatrix = function (view, projection) {
  26009. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26010. return;
  26011. }
  26012. this._viewUpdateFlag = view.updateFlag;
  26013. this._projectionUpdateFlag = projection.updateFlag;
  26014. this._viewMatrix = view;
  26015. this._projectionMatrix = projection;
  26016. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26017. // Update frustum
  26018. if (!this._frustumPlanes) {
  26019. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26020. }
  26021. else {
  26022. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26023. }
  26024. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26025. var otherCamera = this.activeCamera._alternateCamera;
  26026. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26027. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26028. }
  26029. if (this._sceneUbo.useUbo) {
  26030. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26031. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26032. this._sceneUbo.update();
  26033. }
  26034. };
  26035. /** @hidden */
  26036. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26037. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26038. return;
  26039. }
  26040. this._alternateViewUpdateFlag = view.updateFlag;
  26041. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26042. this._alternateViewMatrix = view;
  26043. this._alternateProjectionMatrix = projection;
  26044. if (!this._alternateTransformMatrix) {
  26045. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26046. }
  26047. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26048. if (!this._alternateSceneUbo) {
  26049. this._createAlternateUbo();
  26050. }
  26051. if (this._alternateSceneUbo.useUbo) {
  26052. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26053. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26054. this._alternateSceneUbo.update();
  26055. }
  26056. };
  26057. /**
  26058. * Gets the uniform buffer used to store scene data
  26059. * @returns a UniformBuffer
  26060. */
  26061. Scene.prototype.getSceneUniformBuffer = function () {
  26062. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26063. };
  26064. /**
  26065. * Gets an unique (relatively to the current scene) Id
  26066. * @returns an unique number for the scene
  26067. */
  26068. Scene.prototype.getUniqueId = function () {
  26069. var result = Scene._uniqueIdCounter;
  26070. Scene._uniqueIdCounter++;
  26071. return result;
  26072. };
  26073. /**
  26074. * Add a mesh to the list of scene's meshes
  26075. * @param newMesh defines the mesh to add
  26076. * @param recursive if all child meshes should also be added to the scene
  26077. */
  26078. Scene.prototype.addMesh = function (newMesh, recursive) {
  26079. var _this = this;
  26080. if (recursive === void 0) { recursive = false; }
  26081. this.meshes.push(newMesh);
  26082. //notify the collision coordinator
  26083. if (this.collisionCoordinator) {
  26084. this.collisionCoordinator.onMeshAdded(newMesh);
  26085. }
  26086. newMesh._resyncLightSources();
  26087. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26088. if (recursive) {
  26089. newMesh.getChildMeshes().forEach(function (m) {
  26090. _this.addMesh(m);
  26091. });
  26092. }
  26093. };
  26094. /**
  26095. * Remove a mesh for the list of scene's meshes
  26096. * @param toRemove defines the mesh to remove
  26097. * @param recursive if all child meshes should also be removed from the scene
  26098. * @returns the index where the mesh was in the mesh list
  26099. */
  26100. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26101. var _this = this;
  26102. if (recursive === void 0) { recursive = false; }
  26103. var index = this.meshes.indexOf(toRemove);
  26104. if (index !== -1) {
  26105. // Remove from the scene if mesh found
  26106. this.meshes.splice(index, 1);
  26107. }
  26108. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26109. if (recursive) {
  26110. toRemove.getChildMeshes().forEach(function (m) {
  26111. _this.removeMesh(m);
  26112. });
  26113. }
  26114. return index;
  26115. };
  26116. /**
  26117. * Add a transform node to the list of scene's transform nodes
  26118. * @param newTransformNode defines the transform node to add
  26119. */
  26120. Scene.prototype.addTransformNode = function (newTransformNode) {
  26121. this.transformNodes.push(newTransformNode);
  26122. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26123. };
  26124. /**
  26125. * Remove a transform node for the list of scene's transform nodes
  26126. * @param toRemove defines the transform node to remove
  26127. * @returns the index where the transform node was in the transform node list
  26128. */
  26129. Scene.prototype.removeTransformNode = function (toRemove) {
  26130. var index = this.transformNodes.indexOf(toRemove);
  26131. if (index !== -1) {
  26132. // Remove from the scene if found
  26133. this.transformNodes.splice(index, 1);
  26134. }
  26135. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26136. return index;
  26137. };
  26138. /**
  26139. * Remove a skeleton for the list of scene's skeletons
  26140. * @param toRemove defines the skeleton to remove
  26141. * @returns the index where the skeleton was in the skeleton list
  26142. */
  26143. Scene.prototype.removeSkeleton = function (toRemove) {
  26144. var index = this.skeletons.indexOf(toRemove);
  26145. if (index !== -1) {
  26146. // Remove from the scene if found
  26147. this.skeletons.splice(index, 1);
  26148. }
  26149. return index;
  26150. };
  26151. /**
  26152. * Remove a morph target for the list of scene's morph targets
  26153. * @param toRemove defines the morph target to remove
  26154. * @returns the index where the morph target was in the morph target list
  26155. */
  26156. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26157. var index = this.morphTargetManagers.indexOf(toRemove);
  26158. if (index !== -1) {
  26159. // Remove from the scene if found
  26160. this.morphTargetManagers.splice(index, 1);
  26161. }
  26162. return index;
  26163. };
  26164. /**
  26165. * Remove a light for the list of scene's lights
  26166. * @param toRemove defines the light to remove
  26167. * @returns the index where the light was in the light list
  26168. */
  26169. Scene.prototype.removeLight = function (toRemove) {
  26170. var index = this.lights.indexOf(toRemove);
  26171. if (index !== -1) {
  26172. // Remove from meshes
  26173. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26174. var mesh = _a[_i];
  26175. mesh._removeLightSource(toRemove);
  26176. }
  26177. // Remove from the scene if mesh found
  26178. this.lights.splice(index, 1);
  26179. this.sortLightsByPriority();
  26180. }
  26181. this.onLightRemovedObservable.notifyObservers(toRemove);
  26182. return index;
  26183. };
  26184. /**
  26185. * Remove a camera for the list of scene's cameras
  26186. * @param toRemove defines the camera to remove
  26187. * @returns the index where the camera was in the camera list
  26188. */
  26189. Scene.prototype.removeCamera = function (toRemove) {
  26190. var index = this.cameras.indexOf(toRemove);
  26191. if (index !== -1) {
  26192. // Remove from the scene if mesh found
  26193. this.cameras.splice(index, 1);
  26194. }
  26195. // Remove from activeCameras
  26196. var index2 = this.activeCameras.indexOf(toRemove);
  26197. if (index2 !== -1) {
  26198. // Remove from the scene if mesh found
  26199. this.activeCameras.splice(index2, 1);
  26200. }
  26201. // Reset the activeCamera
  26202. if (this.activeCamera === toRemove) {
  26203. if (this.cameras.length > 0) {
  26204. this.activeCamera = this.cameras[0];
  26205. }
  26206. else {
  26207. this.activeCamera = null;
  26208. }
  26209. }
  26210. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26211. return index;
  26212. };
  26213. /**
  26214. * Remove a particle system for the list of scene's particle systems
  26215. * @param toRemove defines the particle system to remove
  26216. * @returns the index where the particle system was in the particle system list
  26217. */
  26218. Scene.prototype.removeParticleSystem = function (toRemove) {
  26219. var index = this.particleSystems.indexOf(toRemove);
  26220. if (index !== -1) {
  26221. this.particleSystems.splice(index, 1);
  26222. }
  26223. return index;
  26224. };
  26225. /**
  26226. * Remove a animation for the list of scene's animations
  26227. * @param toRemove defines the animation to remove
  26228. * @returns the index where the animation was in the animation list
  26229. */
  26230. Scene.prototype.removeAnimation = function (toRemove) {
  26231. var index = this.animations.indexOf(toRemove);
  26232. if (index !== -1) {
  26233. this.animations.splice(index, 1);
  26234. }
  26235. return index;
  26236. };
  26237. /**
  26238. * Removes the given animation group from this scene.
  26239. * @param toRemove The animation group to remove
  26240. * @returns The index of the removed animation group
  26241. */
  26242. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26243. var index = this.animationGroups.indexOf(toRemove);
  26244. if (index !== -1) {
  26245. this.animationGroups.splice(index, 1);
  26246. }
  26247. return index;
  26248. };
  26249. /**
  26250. * Removes the given multi-material from this scene.
  26251. * @param toRemove The multi-material to remove
  26252. * @returns The index of the removed multi-material
  26253. */
  26254. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26255. var index = this.multiMaterials.indexOf(toRemove);
  26256. if (index !== -1) {
  26257. this.multiMaterials.splice(index, 1);
  26258. }
  26259. return index;
  26260. };
  26261. /**
  26262. * Removes the given material from this scene.
  26263. * @param toRemove The material to remove
  26264. * @returns The index of the removed material
  26265. */
  26266. Scene.prototype.removeMaterial = function (toRemove) {
  26267. var index = this.materials.indexOf(toRemove);
  26268. if (index !== -1) {
  26269. this.materials.splice(index, 1);
  26270. }
  26271. return index;
  26272. };
  26273. /**
  26274. * Removes the given action manager from this scene.
  26275. * @param toRemove The action manager to remove
  26276. * @returns The index of the removed action manager
  26277. */
  26278. Scene.prototype.removeActionManager = function (toRemove) {
  26279. var index = this.actionManagers.indexOf(toRemove);
  26280. if (index !== -1) {
  26281. this.actionManagers.splice(index, 1);
  26282. }
  26283. return index;
  26284. };
  26285. /**
  26286. * Removes the given texture from this scene.
  26287. * @param toRemove The texture to remove
  26288. * @returns The index of the removed texture
  26289. */
  26290. Scene.prototype.removeTexture = function (toRemove) {
  26291. var index = this.textures.indexOf(toRemove);
  26292. if (index !== -1) {
  26293. this.textures.splice(index, 1);
  26294. }
  26295. return index;
  26296. };
  26297. /**
  26298. * Adds the given light to this scene
  26299. * @param newLight The light to add
  26300. */
  26301. Scene.prototype.addLight = function (newLight) {
  26302. this.lights.push(newLight);
  26303. this.sortLightsByPriority();
  26304. // Add light to all meshes (To support if the light is removed and then readded)
  26305. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26306. var mesh = _a[_i];
  26307. if (mesh._lightSources.indexOf(newLight) === -1) {
  26308. mesh._lightSources.push(newLight);
  26309. mesh._resyncLightSources();
  26310. }
  26311. }
  26312. this.onNewLightAddedObservable.notifyObservers(newLight);
  26313. };
  26314. /**
  26315. * Sorts the list list based on light priorities
  26316. */
  26317. Scene.prototype.sortLightsByPriority = function () {
  26318. if (this.requireLightSorting) {
  26319. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26320. }
  26321. };
  26322. /**
  26323. * Adds the given camera to this scene
  26324. * @param newCamera The camera to add
  26325. */
  26326. Scene.prototype.addCamera = function (newCamera) {
  26327. this.cameras.push(newCamera);
  26328. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26329. };
  26330. /**
  26331. * Adds the given skeleton to this scene
  26332. * @param newSkeleton The skeleton to add
  26333. */
  26334. Scene.prototype.addSkeleton = function (newSkeleton) {
  26335. this.skeletons.push(newSkeleton);
  26336. };
  26337. /**
  26338. * Adds the given particle system to this scene
  26339. * @param newParticleSystem The particle system to add
  26340. */
  26341. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26342. this.particleSystems.push(newParticleSystem);
  26343. };
  26344. /**
  26345. * Adds the given animation to this scene
  26346. * @param newAnimation The animation to add
  26347. */
  26348. Scene.prototype.addAnimation = function (newAnimation) {
  26349. this.animations.push(newAnimation);
  26350. };
  26351. /**
  26352. * Adds the given animation group to this scene.
  26353. * @param newAnimationGroup The animation group to add
  26354. */
  26355. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26356. this.animationGroups.push(newAnimationGroup);
  26357. };
  26358. /**
  26359. * Adds the given multi-material to this scene
  26360. * @param newMultiMaterial The multi-material to add
  26361. */
  26362. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26363. this.multiMaterials.push(newMultiMaterial);
  26364. };
  26365. /**
  26366. * Adds the given material to this scene
  26367. * @param newMaterial The material to add
  26368. */
  26369. Scene.prototype.addMaterial = function (newMaterial) {
  26370. this.materials.push(newMaterial);
  26371. };
  26372. /**
  26373. * Adds the given morph target to this scene
  26374. * @param newMorphTargetManager The morph target to add
  26375. */
  26376. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26377. this.morphTargetManagers.push(newMorphTargetManager);
  26378. };
  26379. /**
  26380. * Adds the given geometry to this scene
  26381. * @param newGeometry The geometry to add
  26382. */
  26383. Scene.prototype.addGeometry = function (newGeometry) {
  26384. this.geometries.push(newGeometry);
  26385. };
  26386. /**
  26387. * Adds the given action manager to this scene
  26388. * @param newActionManager The action manager to add
  26389. */
  26390. Scene.prototype.addActionManager = function (newActionManager) {
  26391. this.actionManagers.push(newActionManager);
  26392. };
  26393. /**
  26394. * Adds the given texture to this scene.
  26395. * @param newTexture The texture to add
  26396. */
  26397. Scene.prototype.addTexture = function (newTexture) {
  26398. this.textures.push(newTexture);
  26399. };
  26400. /**
  26401. * Switch active camera
  26402. * @param newCamera defines the new active camera
  26403. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26404. */
  26405. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26406. if (attachControl === void 0) { attachControl = true; }
  26407. var canvas = this._engine.getRenderingCanvas();
  26408. if (!canvas) {
  26409. return;
  26410. }
  26411. if (this.activeCamera) {
  26412. this.activeCamera.detachControl(canvas);
  26413. }
  26414. this.activeCamera = newCamera;
  26415. if (attachControl) {
  26416. newCamera.attachControl(canvas);
  26417. }
  26418. };
  26419. /**
  26420. * sets the active camera of the scene using its ID
  26421. * @param id defines the camera's ID
  26422. * @return the new active camera or null if none found.
  26423. */
  26424. Scene.prototype.setActiveCameraByID = function (id) {
  26425. var camera = this.getCameraByID(id);
  26426. if (camera) {
  26427. this.activeCamera = camera;
  26428. return camera;
  26429. }
  26430. return null;
  26431. };
  26432. /**
  26433. * sets the active camera of the scene using its name
  26434. * @param name defines the camera's name
  26435. * @returns the new active camera or null if none found.
  26436. */
  26437. Scene.prototype.setActiveCameraByName = function (name) {
  26438. var camera = this.getCameraByName(name);
  26439. if (camera) {
  26440. this.activeCamera = camera;
  26441. return camera;
  26442. }
  26443. return null;
  26444. };
  26445. /**
  26446. * get an animation group using its name
  26447. * @param name defines the material's name
  26448. * @return the animation group or null if none found.
  26449. */
  26450. Scene.prototype.getAnimationGroupByName = function (name) {
  26451. for (var index = 0; index < this.animationGroups.length; index++) {
  26452. if (this.animationGroups[index].name === name) {
  26453. return this.animationGroups[index];
  26454. }
  26455. }
  26456. return null;
  26457. };
  26458. /**
  26459. * get a material using its id
  26460. * @param id defines the material's ID
  26461. * @return the material or null if none found.
  26462. */
  26463. Scene.prototype.getMaterialByID = function (id) {
  26464. for (var index = 0; index < this.materials.length; index++) {
  26465. if (this.materials[index].id === id) {
  26466. return this.materials[index];
  26467. }
  26468. }
  26469. return null;
  26470. };
  26471. /**
  26472. * Gets a material using its name
  26473. * @param name defines the material's name
  26474. * @return the material or null if none found.
  26475. */
  26476. Scene.prototype.getMaterialByName = function (name) {
  26477. for (var index = 0; index < this.materials.length; index++) {
  26478. if (this.materials[index].name === name) {
  26479. return this.materials[index];
  26480. }
  26481. }
  26482. return null;
  26483. };
  26484. /**
  26485. * Gets a camera using its id
  26486. * @param id defines the id to look for
  26487. * @returns the camera or null if not found
  26488. */
  26489. Scene.prototype.getCameraByID = function (id) {
  26490. for (var index = 0; index < this.cameras.length; index++) {
  26491. if (this.cameras[index].id === id) {
  26492. return this.cameras[index];
  26493. }
  26494. }
  26495. return null;
  26496. };
  26497. /**
  26498. * Gets a camera using its unique id
  26499. * @param uniqueId defines the unique id to look for
  26500. * @returns the camera or null if not found
  26501. */
  26502. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26503. for (var index = 0; index < this.cameras.length; index++) {
  26504. if (this.cameras[index].uniqueId === uniqueId) {
  26505. return this.cameras[index];
  26506. }
  26507. }
  26508. return null;
  26509. };
  26510. /**
  26511. * Gets a camera using its name
  26512. * @param name defines the camera's name
  26513. * @return the camera or null if none found.
  26514. */
  26515. Scene.prototype.getCameraByName = function (name) {
  26516. for (var index = 0; index < this.cameras.length; index++) {
  26517. if (this.cameras[index].name === name) {
  26518. return this.cameras[index];
  26519. }
  26520. }
  26521. return null;
  26522. };
  26523. /**
  26524. * Gets a bone using its id
  26525. * @param id defines the bone's id
  26526. * @return the bone or null if not found
  26527. */
  26528. Scene.prototype.getBoneByID = function (id) {
  26529. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26530. var skeleton = this.skeletons[skeletonIndex];
  26531. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26532. if (skeleton.bones[boneIndex].id === id) {
  26533. return skeleton.bones[boneIndex];
  26534. }
  26535. }
  26536. }
  26537. return null;
  26538. };
  26539. /**
  26540. * Gets a bone using its id
  26541. * @param name defines the bone's name
  26542. * @return the bone or null if not found
  26543. */
  26544. Scene.prototype.getBoneByName = function (name) {
  26545. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26546. var skeleton = this.skeletons[skeletonIndex];
  26547. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26548. if (skeleton.bones[boneIndex].name === name) {
  26549. return skeleton.bones[boneIndex];
  26550. }
  26551. }
  26552. }
  26553. return null;
  26554. };
  26555. /**
  26556. * Gets a light node using its name
  26557. * @param name defines the the light's name
  26558. * @return the light or null if none found.
  26559. */
  26560. Scene.prototype.getLightByName = function (name) {
  26561. for (var index = 0; index < this.lights.length; index++) {
  26562. if (this.lights[index].name === name) {
  26563. return this.lights[index];
  26564. }
  26565. }
  26566. return null;
  26567. };
  26568. /**
  26569. * Gets a light node using its id
  26570. * @param id defines the light's id
  26571. * @return the light or null if none found.
  26572. */
  26573. Scene.prototype.getLightByID = function (id) {
  26574. for (var index = 0; index < this.lights.length; index++) {
  26575. if (this.lights[index].id === id) {
  26576. return this.lights[index];
  26577. }
  26578. }
  26579. return null;
  26580. };
  26581. /**
  26582. * Gets a light node using its scene-generated unique ID
  26583. * @param uniqueId defines the light's unique id
  26584. * @return the light or null if none found.
  26585. */
  26586. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26587. for (var index = 0; index < this.lights.length; index++) {
  26588. if (this.lights[index].uniqueId === uniqueId) {
  26589. return this.lights[index];
  26590. }
  26591. }
  26592. return null;
  26593. };
  26594. /**
  26595. * Gets a particle system by id
  26596. * @param id defines the particle system id
  26597. * @return the corresponding system or null if none found
  26598. */
  26599. Scene.prototype.getParticleSystemByID = function (id) {
  26600. for (var index = 0; index < this.particleSystems.length; index++) {
  26601. if (this.particleSystems[index].id === id) {
  26602. return this.particleSystems[index];
  26603. }
  26604. }
  26605. return null;
  26606. };
  26607. /**
  26608. * Gets a geometry using its ID
  26609. * @param id defines the geometry's id
  26610. * @return the geometry or null if none found.
  26611. */
  26612. Scene.prototype.getGeometryByID = function (id) {
  26613. for (var index = 0; index < this.geometries.length; index++) {
  26614. if (this.geometries[index].id === id) {
  26615. return this.geometries[index];
  26616. }
  26617. }
  26618. return null;
  26619. };
  26620. /**
  26621. * Add a new geometry to this scene
  26622. * @param geometry defines the geometry to be added to the scene.
  26623. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26624. * @return a boolean defining if the geometry was added or not
  26625. */
  26626. Scene.prototype.pushGeometry = function (geometry, force) {
  26627. if (!force && this.getGeometryByID(geometry.id)) {
  26628. return false;
  26629. }
  26630. this.geometries.push(geometry);
  26631. //notify the collision coordinator
  26632. if (this.collisionCoordinator) {
  26633. this.collisionCoordinator.onGeometryAdded(geometry);
  26634. }
  26635. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26636. return true;
  26637. };
  26638. /**
  26639. * Removes an existing geometry
  26640. * @param geometry defines the geometry to be removed from the scene
  26641. * @return a boolean defining if the geometry was removed or not
  26642. */
  26643. Scene.prototype.removeGeometry = function (geometry) {
  26644. var index = this.geometries.indexOf(geometry);
  26645. if (index > -1) {
  26646. this.geometries.splice(index, 1);
  26647. //notify the collision coordinator
  26648. if (this.collisionCoordinator) {
  26649. this.collisionCoordinator.onGeometryDeleted(geometry);
  26650. }
  26651. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26652. return true;
  26653. }
  26654. return false;
  26655. };
  26656. /**
  26657. * Gets the list of geometries attached to the scene
  26658. * @returns an array of Geometry
  26659. */
  26660. Scene.prototype.getGeometries = function () {
  26661. return this.geometries;
  26662. };
  26663. /**
  26664. * Gets the first added mesh found of a given ID
  26665. * @param id defines the id to search for
  26666. * @return the mesh found or null if not found at all
  26667. */
  26668. Scene.prototype.getMeshByID = function (id) {
  26669. for (var index = 0; index < this.meshes.length; index++) {
  26670. if (this.meshes[index].id === id) {
  26671. return this.meshes[index];
  26672. }
  26673. }
  26674. return null;
  26675. };
  26676. /**
  26677. * Gets a list of meshes using their id
  26678. * @param id defines the id to search for
  26679. * @returns a list of meshes
  26680. */
  26681. Scene.prototype.getMeshesByID = function (id) {
  26682. return this.meshes.filter(function (m) {
  26683. return m.id === id;
  26684. });
  26685. };
  26686. /**
  26687. * Gets the first added transform node found of a given ID
  26688. * @param id defines the id to search for
  26689. * @return the found transform node or null if not found at all.
  26690. */
  26691. Scene.prototype.getTransformNodeByID = function (id) {
  26692. for (var index = 0; index < this.transformNodes.length; index++) {
  26693. if (this.transformNodes[index].id === id) {
  26694. return this.transformNodes[index];
  26695. }
  26696. }
  26697. return null;
  26698. };
  26699. /**
  26700. * Gets a list of transform nodes using their id
  26701. * @param id defines the id to search for
  26702. * @returns a list of transform nodes
  26703. */
  26704. Scene.prototype.getTransformNodesByID = function (id) {
  26705. return this.transformNodes.filter(function (m) {
  26706. return m.id === id;
  26707. });
  26708. };
  26709. /**
  26710. * Gets a mesh with its auto-generated unique id
  26711. * @param uniqueId defines the unique id to search for
  26712. * @return the found mesh or null if not found at all.
  26713. */
  26714. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26715. for (var index = 0; index < this.meshes.length; index++) {
  26716. if (this.meshes[index].uniqueId === uniqueId) {
  26717. return this.meshes[index];
  26718. }
  26719. }
  26720. return null;
  26721. };
  26722. /**
  26723. * Gets a the last added mesh using a given id
  26724. * @param id defines the id to search for
  26725. * @return the found mesh or null if not found at all.
  26726. */
  26727. Scene.prototype.getLastMeshByID = function (id) {
  26728. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26729. if (this.meshes[index].id === id) {
  26730. return this.meshes[index];
  26731. }
  26732. }
  26733. return null;
  26734. };
  26735. /**
  26736. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26737. * @param id defines the id to search for
  26738. * @return the found node or null if not found at all
  26739. */
  26740. Scene.prototype.getLastEntryByID = function (id) {
  26741. var index;
  26742. for (index = this.meshes.length - 1; index >= 0; index--) {
  26743. if (this.meshes[index].id === id) {
  26744. return this.meshes[index];
  26745. }
  26746. }
  26747. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26748. if (this.transformNodes[index].id === id) {
  26749. return this.transformNodes[index];
  26750. }
  26751. }
  26752. for (index = this.cameras.length - 1; index >= 0; index--) {
  26753. if (this.cameras[index].id === id) {
  26754. return this.cameras[index];
  26755. }
  26756. }
  26757. for (index = this.lights.length - 1; index >= 0; index--) {
  26758. if (this.lights[index].id === id) {
  26759. return this.lights[index];
  26760. }
  26761. }
  26762. return null;
  26763. };
  26764. /**
  26765. * Gets a node (Mesh, Camera, Light) using a given id
  26766. * @param id defines the id to search for
  26767. * @return the found node or null if not found at all
  26768. */
  26769. Scene.prototype.getNodeByID = function (id) {
  26770. var mesh = this.getMeshByID(id);
  26771. if (mesh) {
  26772. return mesh;
  26773. }
  26774. var light = this.getLightByID(id);
  26775. if (light) {
  26776. return light;
  26777. }
  26778. var camera = this.getCameraByID(id);
  26779. if (camera) {
  26780. return camera;
  26781. }
  26782. var bone = this.getBoneByID(id);
  26783. return bone;
  26784. };
  26785. /**
  26786. * Gets a node (Mesh, Camera, Light) using a given name
  26787. * @param name defines the name to search for
  26788. * @return the found node or null if not found at all.
  26789. */
  26790. Scene.prototype.getNodeByName = function (name) {
  26791. var mesh = this.getMeshByName(name);
  26792. if (mesh) {
  26793. return mesh;
  26794. }
  26795. var light = this.getLightByName(name);
  26796. if (light) {
  26797. return light;
  26798. }
  26799. var camera = this.getCameraByName(name);
  26800. if (camera) {
  26801. return camera;
  26802. }
  26803. var bone = this.getBoneByName(name);
  26804. return bone;
  26805. };
  26806. /**
  26807. * Gets a mesh using a given name
  26808. * @param name defines the name to search for
  26809. * @return the found mesh or null if not found at all.
  26810. */
  26811. Scene.prototype.getMeshByName = function (name) {
  26812. for (var index = 0; index < this.meshes.length; index++) {
  26813. if (this.meshes[index].name === name) {
  26814. return this.meshes[index];
  26815. }
  26816. }
  26817. return null;
  26818. };
  26819. /**
  26820. * Gets a transform node using a given name
  26821. * @param name defines the name to search for
  26822. * @return the found transform node or null if not found at all.
  26823. */
  26824. Scene.prototype.getTransformNodeByName = function (name) {
  26825. for (var index = 0; index < this.transformNodes.length; index++) {
  26826. if (this.transformNodes[index].name === name) {
  26827. return this.transformNodes[index];
  26828. }
  26829. }
  26830. return null;
  26831. };
  26832. /**
  26833. * Gets a sound using a given name
  26834. * @param name defines the name to search for
  26835. * @return the found sound or null if not found at all.
  26836. */
  26837. Scene.prototype.getSoundByName = function (name) {
  26838. var index;
  26839. if (BABYLON.AudioEngine) {
  26840. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26841. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26842. return this.mainSoundTrack.soundCollection[index];
  26843. }
  26844. }
  26845. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26846. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26847. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26848. return this.soundTracks[sdIndex].soundCollection[index];
  26849. }
  26850. }
  26851. }
  26852. }
  26853. return null;
  26854. };
  26855. /**
  26856. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26857. * @param id defines the id to search for
  26858. * @return the found skeleton or null if not found at all.
  26859. */
  26860. Scene.prototype.getLastSkeletonByID = function (id) {
  26861. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26862. if (this.skeletons[index].id === id) {
  26863. return this.skeletons[index];
  26864. }
  26865. }
  26866. return null;
  26867. };
  26868. /**
  26869. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26870. * @param id defines the id to search for
  26871. * @return the found skeleton or null if not found at all.
  26872. */
  26873. Scene.prototype.getSkeletonById = function (id) {
  26874. for (var index = 0; index < this.skeletons.length; index++) {
  26875. if (this.skeletons[index].id === id) {
  26876. return this.skeletons[index];
  26877. }
  26878. }
  26879. return null;
  26880. };
  26881. /**
  26882. * Gets a skeleton using a given name
  26883. * @param name defines the name to search for
  26884. * @return the found skeleton or null if not found at all.
  26885. */
  26886. Scene.prototype.getSkeletonByName = function (name) {
  26887. for (var index = 0; index < this.skeletons.length; index++) {
  26888. if (this.skeletons[index].name === name) {
  26889. return this.skeletons[index];
  26890. }
  26891. }
  26892. return null;
  26893. };
  26894. /**
  26895. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26896. * @param id defines the id to search for
  26897. * @return the found morph target manager or null if not found at all.
  26898. */
  26899. Scene.prototype.getMorphTargetManagerById = function (id) {
  26900. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26901. if (this.morphTargetManagers[index].uniqueId === id) {
  26902. return this.morphTargetManagers[index];
  26903. }
  26904. }
  26905. return null;
  26906. };
  26907. /**
  26908. * Gets a boolean indicating if the given mesh is active
  26909. * @param mesh defines the mesh to look for
  26910. * @returns true if the mesh is in the active list
  26911. */
  26912. Scene.prototype.isActiveMesh = function (mesh) {
  26913. return (this._activeMeshes.indexOf(mesh) !== -1);
  26914. };
  26915. Object.defineProperty(Scene.prototype, "uid", {
  26916. /**
  26917. * Return a unique id as a string which can serve as an identifier for the scene
  26918. */
  26919. get: function () {
  26920. if (!this._uid) {
  26921. this._uid = BABYLON.Tools.RandomId();
  26922. }
  26923. return this._uid;
  26924. },
  26925. enumerable: true,
  26926. configurable: true
  26927. });
  26928. /**
  26929. * Add an externaly attached data from its key.
  26930. * This method call will fail and return false, if such key already exists.
  26931. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26932. * @param key the unique key that identifies the data
  26933. * @param data the data object to associate to the key for this Engine instance
  26934. * @return true if no such key were already present and the data was added successfully, false otherwise
  26935. */
  26936. Scene.prototype.addExternalData = function (key, data) {
  26937. if (!this._externalData) {
  26938. this._externalData = new BABYLON.StringDictionary();
  26939. }
  26940. return this._externalData.add(key, data);
  26941. };
  26942. /**
  26943. * Get an externaly attached data from its key
  26944. * @param key the unique key that identifies the data
  26945. * @return the associated data, if present (can be null), or undefined if not present
  26946. */
  26947. Scene.prototype.getExternalData = function (key) {
  26948. if (!this._externalData) {
  26949. return null;
  26950. }
  26951. return this._externalData.get(key);
  26952. };
  26953. /**
  26954. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26955. * @param key the unique key that identifies the data
  26956. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26957. * @return the associated data, can be null if the factory returned null.
  26958. */
  26959. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26960. if (!this._externalData) {
  26961. this._externalData = new BABYLON.StringDictionary();
  26962. }
  26963. return this._externalData.getOrAddWithFactory(key, factory);
  26964. };
  26965. /**
  26966. * Remove an externaly attached data from the Engine instance
  26967. * @param key the unique key that identifies the data
  26968. * @return true if the data was successfully removed, false if it doesn't exist
  26969. */
  26970. Scene.prototype.removeExternalData = function (key) {
  26971. return this._externalData.remove(key);
  26972. };
  26973. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26974. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26975. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  26976. var step = _a[_i];
  26977. step.action(mesh, subMesh);
  26978. }
  26979. var material = subMesh.getMaterial();
  26980. if (material !== null && material !== undefined) {
  26981. // Render targets
  26982. if (material.getRenderTargetTextures !== undefined) {
  26983. if (this._processedMaterials.indexOf(material) === -1) {
  26984. this._processedMaterials.push(material);
  26985. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26986. }
  26987. }
  26988. // Dispatch
  26989. this._activeIndices.addCount(subMesh.indexCount, false);
  26990. this._renderingManager.dispatch(subMesh, mesh, material);
  26991. }
  26992. }
  26993. };
  26994. /**
  26995. * Clear the processed materials smart array preventing retention point in material dispose.
  26996. */
  26997. Scene.prototype.freeProcessedMaterials = function () {
  26998. this._processedMaterials.dispose();
  26999. };
  27000. /**
  27001. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27002. */
  27003. Scene.prototype.freeActiveMeshes = function () {
  27004. this._activeMeshes.dispose();
  27005. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27006. this.activeCamera._activeMeshes.dispose();
  27007. }
  27008. if (this.activeCameras) {
  27009. for (var i = 0; i < this.activeCameras.length; i++) {
  27010. var activeCamera = this.activeCameras[i];
  27011. if (activeCamera && activeCamera._activeMeshes) {
  27012. activeCamera._activeMeshes.dispose();
  27013. }
  27014. }
  27015. }
  27016. };
  27017. /**
  27018. * Clear the info related to rendering groups preventing retention points during dispose.
  27019. */
  27020. Scene.prototype.freeRenderingGroups = function () {
  27021. if (this._renderingManager) {
  27022. this._renderingManager.freeRenderingGroups();
  27023. }
  27024. if (this.textures) {
  27025. for (var i = 0; i < this.textures.length; i++) {
  27026. var texture = this.textures[i];
  27027. if (texture && texture.renderList) {
  27028. texture.freeRenderingGroups();
  27029. }
  27030. }
  27031. }
  27032. };
  27033. /** @hidden */
  27034. Scene.prototype._isInIntermediateRendering = function () {
  27035. return this._intermediateRendering;
  27036. };
  27037. /**
  27038. * Defines the current active mesh candidate provider
  27039. * @param provider defines the provider to use
  27040. */
  27041. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27042. this._activeMeshCandidateProvider = provider;
  27043. };
  27044. /**
  27045. * Gets the current active mesh candidate provider
  27046. * @returns the current active mesh candidate provider
  27047. */
  27048. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27049. return this._activeMeshCandidateProvider;
  27050. };
  27051. /**
  27052. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27053. * @returns the current scene
  27054. */
  27055. Scene.prototype.freezeActiveMeshes = function () {
  27056. if (!this.activeCamera) {
  27057. return this;
  27058. }
  27059. if (!this._frustumPlanes) {
  27060. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27061. }
  27062. this._evaluateActiveMeshes();
  27063. this._activeMeshesFrozen = true;
  27064. return this;
  27065. };
  27066. /**
  27067. * Use this function to restart evaluating active meshes on every frame
  27068. * @returns the current scene
  27069. */
  27070. Scene.prototype.unfreezeActiveMeshes = function () {
  27071. this._activeMeshesFrozen = false;
  27072. return this;
  27073. };
  27074. Scene.prototype._evaluateActiveMeshes = function () {
  27075. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27076. return;
  27077. }
  27078. if (!this.activeCamera) {
  27079. return;
  27080. }
  27081. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27082. this.activeCamera._activeMeshes.reset();
  27083. this._activeMeshes.reset();
  27084. this._renderingManager.reset();
  27085. this._processedMaterials.reset();
  27086. this._activeParticleSystems.reset();
  27087. this._activeSkeletons.reset();
  27088. this._softwareSkinnedMeshes.reset();
  27089. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27090. var step = _a[_i];
  27091. step.action();
  27092. }
  27093. // Meshes
  27094. var meshes;
  27095. var len;
  27096. var checkIsEnabled = true;
  27097. // Determine mesh candidates
  27098. if (this._activeMeshCandidateProvider !== undefined) {
  27099. // Use _activeMeshCandidateProvider
  27100. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27101. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27102. if (meshes !== undefined) {
  27103. len = meshes.length;
  27104. }
  27105. else {
  27106. len = 0;
  27107. }
  27108. }
  27109. else if (this._selectionOctree !== undefined) {
  27110. // Octree
  27111. var selection = this._selectionOctree.select(this._frustumPlanes);
  27112. meshes = selection.data;
  27113. len = selection.length;
  27114. }
  27115. else {
  27116. // Full scene traversal
  27117. len = this.meshes.length;
  27118. meshes = this.meshes;
  27119. }
  27120. // Check each mesh
  27121. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27122. mesh = meshes[meshIndex];
  27123. if (mesh.isBlocked) {
  27124. continue;
  27125. }
  27126. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27127. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27128. continue;
  27129. }
  27130. mesh.computeWorldMatrix();
  27131. // Intersections
  27132. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27133. this._meshesForIntersections.pushNoDuplicate(mesh);
  27134. }
  27135. // Switch to current LOD
  27136. meshLOD = mesh.getLOD(this.activeCamera);
  27137. if (meshLOD === undefined || meshLOD === null) {
  27138. continue;
  27139. }
  27140. mesh._preActivate();
  27141. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27142. this._activeMeshes.push(mesh);
  27143. this.activeCamera._activeMeshes.push(mesh);
  27144. mesh._activate(this._renderId);
  27145. if (meshLOD !== mesh) {
  27146. meshLOD._activate(this._renderId);
  27147. }
  27148. this._activeMesh(mesh, meshLOD);
  27149. }
  27150. }
  27151. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27152. // Particle systems
  27153. if (this.particlesEnabled) {
  27154. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27155. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27156. var particleSystem = this.particleSystems[particleIndex];
  27157. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27158. continue;
  27159. }
  27160. var emitter = particleSystem.emitter;
  27161. if (!emitter.position || emitter.isEnabled()) {
  27162. this._activeParticleSystems.push(particleSystem);
  27163. particleSystem.animate();
  27164. this._renderingManager.dispatchParticles(particleSystem);
  27165. }
  27166. }
  27167. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27168. }
  27169. };
  27170. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27171. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27172. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27173. mesh.skeleton.prepare();
  27174. }
  27175. if (!mesh.computeBonesUsingShaders) {
  27176. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27177. }
  27178. }
  27179. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27180. var step = _a[_i];
  27181. step.action(sourceMesh, mesh);
  27182. }
  27183. if (mesh !== undefined && mesh !== null
  27184. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27185. // Submeshes Octrees
  27186. var len;
  27187. var subMeshes;
  27188. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27189. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27190. len = intersections.length;
  27191. subMeshes = intersections.data;
  27192. }
  27193. else {
  27194. subMeshes = mesh.subMeshes;
  27195. len = subMeshes.length;
  27196. }
  27197. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27198. subMesh = subMeshes[subIndex];
  27199. this._evaluateSubMesh(subMesh, mesh);
  27200. }
  27201. }
  27202. };
  27203. /**
  27204. * Update the transform matrix to update from the current active camera
  27205. * @param force defines a boolean used to force the update even if cache is up to date
  27206. */
  27207. Scene.prototype.updateTransformMatrix = function (force) {
  27208. if (!this.activeCamera) {
  27209. return;
  27210. }
  27211. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27212. };
  27213. /**
  27214. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27215. * @param alternateCamera defines the camera to use
  27216. */
  27217. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27218. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27219. };
  27220. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27221. if (camera && camera._skipRendering) {
  27222. return;
  27223. }
  27224. var engine = this._engine;
  27225. this.activeCamera = camera;
  27226. if (!this.activeCamera)
  27227. throw new Error("Active camera not set");
  27228. // Viewport
  27229. engine.setViewport(this.activeCamera.viewport);
  27230. // Camera
  27231. this.resetCachedMaterial();
  27232. this._renderId++;
  27233. this.updateTransformMatrix();
  27234. if (camera._alternateCamera) {
  27235. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27236. this._alternateRendering = true;
  27237. }
  27238. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27239. // Meshes
  27240. this._evaluateActiveMeshes();
  27241. // Software skinning
  27242. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27243. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27244. mesh.applySkeleton(mesh.skeleton);
  27245. }
  27246. // Render targets
  27247. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27248. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27249. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27250. }
  27251. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27252. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27253. }
  27254. if (this.renderTargetsEnabled) {
  27255. this._intermediateRendering = true;
  27256. if (this._renderTargets.length > 0) {
  27257. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27258. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27259. var renderTarget = this._renderTargets.data[renderIndex];
  27260. if (renderTarget._shouldRender()) {
  27261. this._renderId++;
  27262. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27263. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27264. }
  27265. }
  27266. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27267. this._renderId++;
  27268. }
  27269. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27270. var step = _a[_i];
  27271. step.action(this.activeCamera);
  27272. }
  27273. this._intermediateRendering = false;
  27274. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27275. }
  27276. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27277. // Prepare Frame
  27278. if (this.postProcessManager) {
  27279. this.postProcessManager._prepareFrame();
  27280. }
  27281. // Before Camera Draw
  27282. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27283. var step = _c[_b];
  27284. step.action(this.activeCamera);
  27285. }
  27286. // Render
  27287. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27288. this._renderingManager.render(null, null, true, true);
  27289. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27290. // After Camera Draw
  27291. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27292. var step = _e[_d];
  27293. step.action(this.activeCamera);
  27294. }
  27295. // Finalize frame
  27296. if (this.postProcessManager) {
  27297. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27298. }
  27299. // Reset some special arrays
  27300. this._renderTargets.reset();
  27301. this._alternateRendering = false;
  27302. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27303. };
  27304. Scene.prototype._processSubCameras = function (camera) {
  27305. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27306. this._renderForCamera(camera);
  27307. return;
  27308. }
  27309. // rig cameras
  27310. for (var index = 0; index < camera._rigCameras.length; index++) {
  27311. this._renderForCamera(camera._rigCameras[index], camera);
  27312. }
  27313. this.activeCamera = camera;
  27314. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27315. };
  27316. Scene.prototype._checkIntersections = function () {
  27317. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27318. var sourceMesh = this._meshesForIntersections.data[index];
  27319. if (!sourceMesh.actionManager) {
  27320. continue;
  27321. }
  27322. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27323. var action = sourceMesh.actionManager.actions[actionIndex];
  27324. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27325. var parameters = action.getTriggerParameter();
  27326. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27327. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27328. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27329. if (areIntersecting && currentIntersectionInProgress === -1) {
  27330. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27331. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27332. sourceMesh._intersectionsInProgress.push(otherMesh);
  27333. }
  27334. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27335. sourceMesh._intersectionsInProgress.push(otherMesh);
  27336. }
  27337. }
  27338. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27339. //They intersected, and now they don't.
  27340. //is this trigger an exit trigger? execute an event.
  27341. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27342. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27343. }
  27344. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27345. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27346. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27347. return otherMesh === parameterMesh;
  27348. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27349. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27350. }
  27351. }
  27352. }
  27353. }
  27354. }
  27355. };
  27356. /**
  27357. * Render the scene
  27358. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27359. */
  27360. Scene.prototype.render = function (updateCameras) {
  27361. if (updateCameras === void 0) { updateCameras = true; }
  27362. if (this.isDisposed) {
  27363. return;
  27364. }
  27365. // Register components that have been associated lately to the scene.
  27366. this._registerTransientComponents();
  27367. this._activeParticles.fetchNewFrame();
  27368. this._totalVertices.fetchNewFrame();
  27369. this._activeIndices.fetchNewFrame();
  27370. this._activeBones.fetchNewFrame();
  27371. this._meshesForIntersections.reset();
  27372. this.resetCachedMaterial();
  27373. this.onBeforeAnimationsObservable.notifyObservers(this);
  27374. // Actions
  27375. if (this.actionManager) {
  27376. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27377. }
  27378. //Simplification Queue
  27379. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27380. this.simplificationQueue.executeNext();
  27381. }
  27382. if (this._engine.isDeterministicLockStep()) {
  27383. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27384. var defaultFPS = (60.0 / 1000.0);
  27385. var defaultFrameTime = 1000 / 60; // frame time in MS
  27386. if (this._physicsEngine) {
  27387. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27388. }
  27389. var stepsTaken = 0;
  27390. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27391. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27392. internalSteps = Math.min(internalSteps, maxSubSteps);
  27393. do {
  27394. this.onBeforeStepObservable.notifyObservers(this);
  27395. // Animations
  27396. this._animationRatio = defaultFrameTime * defaultFPS;
  27397. this._animate();
  27398. this.onAfterAnimationsObservable.notifyObservers(this);
  27399. // Physics
  27400. if (this._physicsEngine) {
  27401. this.onBeforePhysicsObservable.notifyObservers(this);
  27402. this._physicsEngine._step(defaultFrameTime / 1000);
  27403. this.onAfterPhysicsObservable.notifyObservers(this);
  27404. }
  27405. this.onAfterStepObservable.notifyObservers(this);
  27406. this._currentStepId++;
  27407. stepsTaken++;
  27408. deltaTime -= defaultFrameTime;
  27409. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27410. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27411. }
  27412. else {
  27413. // Animations
  27414. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27415. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27416. this._animate();
  27417. this.onAfterAnimationsObservable.notifyObservers(this);
  27418. // Physics
  27419. if (this._physicsEngine) {
  27420. this.onBeforePhysicsObservable.notifyObservers(this);
  27421. this._physicsEngine._step(deltaTime / 1000.0);
  27422. this.onAfterPhysicsObservable.notifyObservers(this);
  27423. }
  27424. }
  27425. // Before camera update steps
  27426. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27427. var step = _a[_i];
  27428. step.action();
  27429. }
  27430. // Update Cameras
  27431. if (updateCameras) {
  27432. if (this.activeCameras.length > 0) {
  27433. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27434. var camera = this.activeCameras[cameraIndex];
  27435. camera.update();
  27436. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27437. // rig cameras
  27438. for (var index = 0; index < camera._rigCameras.length; index++) {
  27439. camera._rigCameras[index].update();
  27440. }
  27441. }
  27442. }
  27443. }
  27444. else if (this.activeCamera) {
  27445. this.activeCamera.update();
  27446. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27447. // rig cameras
  27448. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27449. this.activeCamera._rigCameras[index].update();
  27450. }
  27451. }
  27452. }
  27453. }
  27454. // Before render
  27455. this.onBeforeRenderObservable.notifyObservers(this);
  27456. // Customs render targets
  27457. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27458. var engine = this.getEngine();
  27459. var currentActiveCamera = this.activeCamera;
  27460. if (this.renderTargetsEnabled) {
  27461. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27462. this._intermediateRendering = true;
  27463. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27464. var renderTarget = this.customRenderTargets[customIndex];
  27465. if (renderTarget._shouldRender()) {
  27466. this._renderId++;
  27467. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27468. if (!this.activeCamera)
  27469. throw new Error("Active camera not set");
  27470. // Viewport
  27471. engine.setViewport(this.activeCamera.viewport);
  27472. // Camera
  27473. this.updateTransformMatrix();
  27474. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27475. }
  27476. }
  27477. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27478. this._intermediateRendering = false;
  27479. this._renderId++;
  27480. }
  27481. // Restore back buffer
  27482. if (this.customRenderTargets.length > 0) {
  27483. engine.restoreDefaultFramebuffer();
  27484. }
  27485. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27486. this.activeCamera = currentActiveCamera;
  27487. // Procedural textures
  27488. if (this.proceduralTexturesEnabled) {
  27489. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27490. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27491. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27492. if (proceduralTexture._shouldRender()) {
  27493. proceduralTexture.render();
  27494. }
  27495. }
  27496. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27497. }
  27498. // Clear
  27499. if (this.autoClearDepthAndStencil || this.autoClear) {
  27500. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27501. }
  27502. // Shadows
  27503. if (this.shadowsEnabled) {
  27504. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27505. var light = this.lights[lightIndex];
  27506. var shadowGenerator = light.getShadowGenerator();
  27507. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27508. var shadowMap = (shadowGenerator.getShadowMap());
  27509. if (this.textures.indexOf(shadowMap) !== -1) {
  27510. this._renderTargets.push(shadowMap);
  27511. }
  27512. }
  27513. }
  27514. }
  27515. // Depth renderer
  27516. for (var key in this._depthRenderer) {
  27517. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27518. }
  27519. // Geometry renderer
  27520. if (this._geometryBufferRenderer) {
  27521. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27522. }
  27523. // RenderPipeline
  27524. if (this._postProcessRenderPipelineManager) {
  27525. this._postProcessRenderPipelineManager.update();
  27526. }
  27527. // Multi-cameras?
  27528. if (this.activeCameras.length > 0) {
  27529. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27530. if (cameraIndex > 0) {
  27531. this._engine.clear(null, false, true, true);
  27532. }
  27533. this._processSubCameras(this.activeCameras[cameraIndex]);
  27534. }
  27535. }
  27536. else {
  27537. if (!this.activeCamera) {
  27538. throw new Error("No camera defined");
  27539. }
  27540. this._processSubCameras(this.activeCamera);
  27541. }
  27542. // Intersection checks
  27543. this._checkIntersections();
  27544. // Update the audio listener attached to the camera
  27545. if (BABYLON.AudioEngine) {
  27546. this._updateAudioParameters();
  27547. }
  27548. // After render
  27549. if (this.afterRender) {
  27550. this.afterRender();
  27551. }
  27552. this.onAfterRenderObservable.notifyObservers(this);
  27553. // Cleaning
  27554. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27555. var data = this._toBeDisposed.data[index];
  27556. if (data) {
  27557. data.dispose();
  27558. }
  27559. this._toBeDisposed[index] = null;
  27560. }
  27561. this._toBeDisposed.reset();
  27562. if (this.dumpNextRenderTargets) {
  27563. this.dumpNextRenderTargets = false;
  27564. }
  27565. this._activeBones.addCount(0, true);
  27566. this._activeIndices.addCount(0, true);
  27567. this._activeParticles.addCount(0, true);
  27568. };
  27569. Scene.prototype._updateAudioParameters = function () {
  27570. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27571. return;
  27572. }
  27573. var listeningCamera;
  27574. var audioEngine = BABYLON.Engine.audioEngine;
  27575. if (this.activeCameras.length > 0) {
  27576. listeningCamera = this.activeCameras[0];
  27577. }
  27578. else {
  27579. listeningCamera = this.activeCamera;
  27580. }
  27581. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27582. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27583. // for VR cameras
  27584. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27585. listeningCamera = listeningCamera.rigCameras[0];
  27586. }
  27587. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27588. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27589. cameraDirection.normalize();
  27590. // To avoid some errors on GearVR
  27591. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27592. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27593. }
  27594. var i;
  27595. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27596. var sound = this.mainSoundTrack.soundCollection[i];
  27597. if (sound.useCustomAttenuation) {
  27598. sound.updateDistanceFromListener();
  27599. }
  27600. }
  27601. for (i = 0; i < this.soundTracks.length; i++) {
  27602. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27603. sound = this.soundTracks[i].soundCollection[j];
  27604. if (sound.useCustomAttenuation) {
  27605. sound.updateDistanceFromListener();
  27606. }
  27607. }
  27608. }
  27609. }
  27610. };
  27611. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27612. // Audio
  27613. /**
  27614. * Gets or sets if audio support is enabled
  27615. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27616. */
  27617. get: function () {
  27618. return this._audioEnabled;
  27619. },
  27620. set: function (value) {
  27621. this._audioEnabled = value;
  27622. if (BABYLON.AudioEngine) {
  27623. if (this._audioEnabled) {
  27624. this._enableAudio();
  27625. }
  27626. else {
  27627. this._disableAudio();
  27628. }
  27629. }
  27630. },
  27631. enumerable: true,
  27632. configurable: true
  27633. });
  27634. Scene.prototype._disableAudio = function () {
  27635. var i;
  27636. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27637. this.mainSoundTrack.soundCollection[i].pause();
  27638. }
  27639. for (i = 0; i < this.soundTracks.length; i++) {
  27640. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27641. this.soundTracks[i].soundCollection[j].pause();
  27642. }
  27643. }
  27644. };
  27645. Scene.prototype._enableAudio = function () {
  27646. var i;
  27647. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27648. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27649. this.mainSoundTrack.soundCollection[i].play();
  27650. }
  27651. }
  27652. for (i = 0; i < this.soundTracks.length; i++) {
  27653. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27654. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27655. this.soundTracks[i].soundCollection[j].play();
  27656. }
  27657. }
  27658. }
  27659. };
  27660. Object.defineProperty(Scene.prototype, "headphone", {
  27661. /**
  27662. * Gets or sets if audio will be output to headphones
  27663. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27664. */
  27665. get: function () {
  27666. return this._headphone;
  27667. },
  27668. set: function (value) {
  27669. this._headphone = value;
  27670. if (BABYLON.AudioEngine) {
  27671. if (this._headphone) {
  27672. this._switchAudioModeForHeadphones();
  27673. }
  27674. else {
  27675. this._switchAudioModeForNormalSpeakers();
  27676. }
  27677. }
  27678. },
  27679. enumerable: true,
  27680. configurable: true
  27681. });
  27682. Scene.prototype._switchAudioModeForHeadphones = function () {
  27683. this.mainSoundTrack.switchPanningModelToHRTF();
  27684. for (var i = 0; i < this.soundTracks.length; i++) {
  27685. this.soundTracks[i].switchPanningModelToHRTF();
  27686. }
  27687. };
  27688. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27689. this.mainSoundTrack.switchPanningModelToEqualPower();
  27690. for (var i = 0; i < this.soundTracks.length; i++) {
  27691. this.soundTracks[i].switchPanningModelToEqualPower();
  27692. }
  27693. };
  27694. /**
  27695. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27696. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27697. * @returns the created depth renderer
  27698. */
  27699. Scene.prototype.enableDepthRenderer = function (camera) {
  27700. camera = camera || this.activeCamera;
  27701. if (!camera) {
  27702. throw "No camera available to enable depth renderer";
  27703. }
  27704. if (!this._depthRenderer[camera.id]) {
  27705. var textureType = 0;
  27706. if (this._engine.getCaps().textureHalfFloatRender) {
  27707. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27708. }
  27709. else if (this._engine.getCaps().textureFloatRender) {
  27710. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27711. }
  27712. else {
  27713. throw "Depth renderer does not support int texture type";
  27714. }
  27715. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27716. }
  27717. return this._depthRenderer[camera.id];
  27718. };
  27719. /**
  27720. * Disables a depth renderer for a given camera
  27721. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27722. */
  27723. Scene.prototype.disableDepthRenderer = function (camera) {
  27724. camera = camera || this.activeCamera;
  27725. if (!camera || !this._depthRenderer[camera.id]) {
  27726. return;
  27727. }
  27728. this._depthRenderer[camera.id].dispose();
  27729. delete this._depthRenderer[camera.id];
  27730. };
  27731. /**
  27732. * Enables a GeometryBufferRender and associates it with the scene
  27733. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27734. * @returns the GeometryBufferRenderer
  27735. */
  27736. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27737. if (ratio === void 0) { ratio = 1; }
  27738. if (this._geometryBufferRenderer) {
  27739. return this._geometryBufferRenderer;
  27740. }
  27741. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27742. if (!this._geometryBufferRenderer.isSupported) {
  27743. this._geometryBufferRenderer = null;
  27744. }
  27745. return this._geometryBufferRenderer;
  27746. };
  27747. /**
  27748. * Disables the GeometryBufferRender associated with the scene
  27749. */
  27750. Scene.prototype.disableGeometryBufferRenderer = function () {
  27751. if (!this._geometryBufferRenderer) {
  27752. return;
  27753. }
  27754. this._geometryBufferRenderer.dispose();
  27755. this._geometryBufferRenderer = null;
  27756. };
  27757. /**
  27758. * Freeze all materials
  27759. * A frozen material will not be updatable but should be faster to render
  27760. */
  27761. Scene.prototype.freezeMaterials = function () {
  27762. for (var i = 0; i < this.materials.length; i++) {
  27763. this.materials[i].freeze();
  27764. }
  27765. };
  27766. /**
  27767. * Unfreeze all materials
  27768. * A frozen material will not be updatable but should be faster to render
  27769. */
  27770. Scene.prototype.unfreezeMaterials = function () {
  27771. for (var i = 0; i < this.materials.length; i++) {
  27772. this.materials[i].unfreeze();
  27773. }
  27774. };
  27775. /**
  27776. * Releases all held ressources
  27777. */
  27778. Scene.prototype.dispose = function () {
  27779. this.beforeRender = null;
  27780. this.afterRender = null;
  27781. this.skeletons = [];
  27782. this.morphTargetManagers = [];
  27783. this._transientComponents = [];
  27784. this._isReadyForMeshStage.clear();
  27785. this._beforeEvaluateActiveMeshStage.clear();
  27786. this._evaluateSubMeshStage.clear();
  27787. this._activeMeshStage.clear();
  27788. this._cameraDrawRenderTargetStage.clear();
  27789. this._beforeCameraDrawStage.clear();
  27790. this._beforeRenderingGroupDrawStage.clear();
  27791. this._afterRenderingGroupDrawStage.clear();
  27792. this._afterCameraDrawStage.clear();
  27793. this._beforeCameraUpdateStage.clear();
  27794. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27795. var component = _a[_i];
  27796. component.dispose();
  27797. }
  27798. this.importedMeshesFiles = new Array();
  27799. this.stopAllAnimations();
  27800. this.resetCachedMaterial();
  27801. for (var key in this._depthRenderer) {
  27802. this._depthRenderer[key].dispose();
  27803. }
  27804. // Smart arrays
  27805. if (this.activeCamera) {
  27806. this.activeCamera._activeMeshes.dispose();
  27807. this.activeCamera = null;
  27808. }
  27809. this._activeMeshes.dispose();
  27810. this._renderingManager.dispose();
  27811. this._processedMaterials.dispose();
  27812. this._activeParticleSystems.dispose();
  27813. this._activeSkeletons.dispose();
  27814. this._softwareSkinnedMeshes.dispose();
  27815. this._renderTargets.dispose();
  27816. this._registeredForLateAnimationBindings.dispose();
  27817. this._meshesForIntersections.dispose();
  27818. this._toBeDisposed.dispose();
  27819. // Abort active requests
  27820. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27821. var request = _c[_b];
  27822. request.abort();
  27823. }
  27824. // Debug layer
  27825. if (this._debugLayer) {
  27826. this._debugLayer.hide();
  27827. }
  27828. // Events
  27829. this.onDisposeObservable.notifyObservers(this);
  27830. this.onDisposeObservable.clear();
  27831. this.onBeforeRenderObservable.clear();
  27832. this.onAfterRenderObservable.clear();
  27833. this.onBeforeRenderTargetsRenderObservable.clear();
  27834. this.onAfterRenderTargetsRenderObservable.clear();
  27835. this.onAfterStepObservable.clear();
  27836. this.onBeforeStepObservable.clear();
  27837. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27838. this.onAfterActiveMeshesEvaluationObservable.clear();
  27839. this.onBeforeParticlesRenderingObservable.clear();
  27840. this.onAfterParticlesRenderingObservable.clear();
  27841. this.onBeforeSpritesRenderingObservable.clear();
  27842. this.onAfterSpritesRenderingObservable.clear();
  27843. this.onBeforeDrawPhaseObservable.clear();
  27844. this.onAfterDrawPhaseObservable.clear();
  27845. this.onBeforePhysicsObservable.clear();
  27846. this.onAfterPhysicsObservable.clear();
  27847. this.onBeforeAnimationsObservable.clear();
  27848. this.onAfterAnimationsObservable.clear();
  27849. this.onDataLoadedObservable.clear();
  27850. this.onBeforeRenderingGroupObservable.clear();
  27851. this.onAfterRenderingGroupObservable.clear();
  27852. this.detachControl();
  27853. // Release sounds & sounds tracks
  27854. if (BABYLON.AudioEngine) {
  27855. this.disposeSounds();
  27856. }
  27857. // VR Helper
  27858. if (this.VRHelper) {
  27859. this.VRHelper.dispose();
  27860. }
  27861. // Detach cameras
  27862. var canvas = this._engine.getRenderingCanvas();
  27863. if (canvas) {
  27864. var index;
  27865. for (index = 0; index < this.cameras.length; index++) {
  27866. this.cameras[index].detachControl(canvas);
  27867. }
  27868. }
  27869. // Release animation groups
  27870. while (this.animationGroups.length) {
  27871. this.animationGroups[0].dispose();
  27872. }
  27873. // Release lights
  27874. while (this.lights.length) {
  27875. this.lights[0].dispose();
  27876. }
  27877. // Release meshes
  27878. while (this.meshes.length) {
  27879. this.meshes[0].dispose(true);
  27880. }
  27881. while (this.transformNodes.length) {
  27882. this.removeTransformNode(this.transformNodes[0]);
  27883. }
  27884. // Release cameras
  27885. while (this.cameras.length) {
  27886. this.cameras[0].dispose();
  27887. }
  27888. // Release materials
  27889. if (this.defaultMaterial) {
  27890. this.defaultMaterial.dispose();
  27891. }
  27892. while (this.multiMaterials.length) {
  27893. this.multiMaterials[0].dispose();
  27894. }
  27895. while (this.materials.length) {
  27896. this.materials[0].dispose();
  27897. }
  27898. // Release particles
  27899. while (this.particleSystems.length) {
  27900. this.particleSystems[0].dispose();
  27901. }
  27902. // Release sprites
  27903. while (this.spriteManagers.length) {
  27904. this.spriteManagers[0].dispose();
  27905. }
  27906. // Release postProcesses
  27907. while (this.postProcesses.length) {
  27908. this.postProcesses[0].dispose();
  27909. }
  27910. // Release textures
  27911. while (this.textures.length) {
  27912. this.textures[0].dispose();
  27913. }
  27914. // Release UBO
  27915. this._sceneUbo.dispose();
  27916. if (this._alternateSceneUbo) {
  27917. this._alternateSceneUbo.dispose();
  27918. }
  27919. // Post-processes
  27920. this.postProcessManager.dispose();
  27921. if (this._postProcessRenderPipelineManager) {
  27922. this._postProcessRenderPipelineManager.dispose();
  27923. }
  27924. // Physics
  27925. if (this._physicsEngine) {
  27926. this.disablePhysicsEngine();
  27927. }
  27928. // Remove from engine
  27929. index = this._engine.scenes.indexOf(this);
  27930. if (index > -1) {
  27931. this._engine.scenes.splice(index, 1);
  27932. }
  27933. this._engine.wipeCaches(true);
  27934. this._isDisposed = true;
  27935. };
  27936. Object.defineProperty(Scene.prototype, "isDisposed", {
  27937. /**
  27938. * Gets if the scene is already disposed
  27939. */
  27940. get: function () {
  27941. return this._isDisposed;
  27942. },
  27943. enumerable: true,
  27944. configurable: true
  27945. });
  27946. /**
  27947. * Releases sounds & soundtracks
  27948. */
  27949. Scene.prototype.disposeSounds = function () {
  27950. if (!this._mainSoundTrack) {
  27951. return;
  27952. }
  27953. this.mainSoundTrack.dispose();
  27954. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27955. this.soundTracks[scIndex].dispose();
  27956. }
  27957. };
  27958. /**
  27959. * Call this function to reduce memory footprint of the scene.
  27960. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  27961. */
  27962. Scene.prototype.clearCachedVertexData = function () {
  27963. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27964. var mesh = this.meshes[meshIndex];
  27965. var geometry = mesh.geometry;
  27966. if (geometry) {
  27967. geometry._indices = [];
  27968. for (var vbName in geometry._vertexBuffers) {
  27969. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  27970. continue;
  27971. }
  27972. geometry._vertexBuffers[vbName]._buffer._data = null;
  27973. }
  27974. }
  27975. }
  27976. };
  27977. /**
  27978. * This function will remove the local cached buffer data from texture.
  27979. * It will save memory but will prevent the texture from being rebuilt
  27980. */
  27981. Scene.prototype.cleanCachedTextureBuffer = function () {
  27982. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27983. var baseTexture = _a[_i];
  27984. var buffer = baseTexture._buffer;
  27985. if (buffer) {
  27986. baseTexture._buffer = null;
  27987. }
  27988. }
  27989. };
  27990. // Octrees
  27991. /**
  27992. * Get the world extend vectors with an optional filter
  27993. *
  27994. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27995. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27996. */
  27997. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27998. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27999. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28000. filterPredicate = filterPredicate || (function () { return true; });
  28001. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28002. mesh.computeWorldMatrix(true);
  28003. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28004. return;
  28005. }
  28006. var boundingInfo = mesh.getBoundingInfo();
  28007. var minBox = boundingInfo.boundingBox.minimumWorld;
  28008. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28009. BABYLON.Tools.CheckExtends(minBox, min, max);
  28010. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28011. });
  28012. return {
  28013. min: min,
  28014. max: max
  28015. };
  28016. };
  28017. /**
  28018. * Creates or updates the octree used to boost selection (picking)
  28019. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28020. * @param maxCapacity defines the maximum capacity per leaf
  28021. * @param maxDepth defines the maximum depth of the octree
  28022. * @returns an octree of AbstractMesh
  28023. */
  28024. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28025. if (maxCapacity === void 0) { maxCapacity = 64; }
  28026. if (maxDepth === void 0) { maxDepth = 2; }
  28027. if (!this._selectionOctree) {
  28028. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28029. }
  28030. var worldExtends = this.getWorldExtends();
  28031. // Update octree
  28032. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28033. return this._selectionOctree;
  28034. };
  28035. // Picking
  28036. /**
  28037. * Creates a ray that can be used to pick in the scene
  28038. * @param x defines the x coordinate of the origin (on-screen)
  28039. * @param y defines the y coordinate of the origin (on-screen)
  28040. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28041. * @param camera defines the camera to use for the picking
  28042. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28043. * @returns a Ray
  28044. */
  28045. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28046. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28047. var result = BABYLON.Ray.Zero();
  28048. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28049. return result;
  28050. };
  28051. /**
  28052. * Creates a ray that can be used to pick in the scene
  28053. * @param x defines the x coordinate of the origin (on-screen)
  28054. * @param y defines the y coordinate of the origin (on-screen)
  28055. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28056. * @param result defines the ray where to store the picking ray
  28057. * @param camera defines the camera to use for the picking
  28058. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28059. * @returns the current scene
  28060. */
  28061. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28062. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28063. var engine = this._engine;
  28064. if (!camera) {
  28065. if (!this.activeCamera)
  28066. throw new Error("Active camera not set");
  28067. camera = this.activeCamera;
  28068. }
  28069. var cameraViewport = camera.viewport;
  28070. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28071. // Moving coordinates to local viewport world
  28072. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28073. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28074. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28075. return this;
  28076. };
  28077. /**
  28078. * Creates a ray that can be used to pick in the scene
  28079. * @param x defines the x coordinate of the origin (on-screen)
  28080. * @param y defines the y coordinate of the origin (on-screen)
  28081. * @param camera defines the camera to use for the picking
  28082. * @returns a Ray
  28083. */
  28084. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28085. var result = BABYLON.Ray.Zero();
  28086. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28087. return result;
  28088. };
  28089. /**
  28090. * Creates a ray that can be used to pick in the scene
  28091. * @param x defines the x coordinate of the origin (on-screen)
  28092. * @param y defines the y coordinate of the origin (on-screen)
  28093. * @param result defines the ray where to store the picking ray
  28094. * @param camera defines the camera to use for the picking
  28095. * @returns the current scene
  28096. */
  28097. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28098. if (!BABYLON.PickingInfo) {
  28099. return this;
  28100. }
  28101. var engine = this._engine;
  28102. if (!camera) {
  28103. if (!this.activeCamera)
  28104. throw new Error("Active camera not set");
  28105. camera = this.activeCamera;
  28106. }
  28107. var cameraViewport = camera.viewport;
  28108. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28109. var identity = BABYLON.Matrix.Identity();
  28110. // Moving coordinates to local viewport world
  28111. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28112. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28113. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28114. return this;
  28115. };
  28116. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28117. if (!BABYLON.PickingInfo) {
  28118. return null;
  28119. }
  28120. var pickingInfo = null;
  28121. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28122. var mesh = this.meshes[meshIndex];
  28123. if (predicate) {
  28124. if (!predicate(mesh)) {
  28125. continue;
  28126. }
  28127. }
  28128. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28129. continue;
  28130. }
  28131. var world = mesh.getWorldMatrix();
  28132. var ray = rayFunction(world);
  28133. var result = mesh.intersects(ray, fastCheck);
  28134. if (!result || !result.hit)
  28135. continue;
  28136. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28137. continue;
  28138. pickingInfo = result;
  28139. if (fastCheck) {
  28140. break;
  28141. }
  28142. }
  28143. return pickingInfo || new BABYLON.PickingInfo();
  28144. };
  28145. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28146. if (!BABYLON.PickingInfo) {
  28147. return null;
  28148. }
  28149. var pickingInfos = new Array();
  28150. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28151. var mesh = this.meshes[meshIndex];
  28152. if (predicate) {
  28153. if (!predicate(mesh)) {
  28154. continue;
  28155. }
  28156. }
  28157. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28158. continue;
  28159. }
  28160. var world = mesh.getWorldMatrix();
  28161. var ray = rayFunction(world);
  28162. var result = mesh.intersects(ray, false);
  28163. if (!result || !result.hit)
  28164. continue;
  28165. pickingInfos.push(result);
  28166. }
  28167. return pickingInfos;
  28168. };
  28169. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28170. if (!BABYLON.PickingInfo) {
  28171. return null;
  28172. }
  28173. var pickingInfo = null;
  28174. if (!camera) {
  28175. if (!this.activeCamera) {
  28176. return null;
  28177. }
  28178. camera = this.activeCamera;
  28179. }
  28180. if (this.spriteManagers.length > 0) {
  28181. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28182. var spriteManager = this.spriteManagers[spriteIndex];
  28183. if (!spriteManager.isPickable) {
  28184. continue;
  28185. }
  28186. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28187. if (!result || !result.hit)
  28188. continue;
  28189. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28190. continue;
  28191. pickingInfo = result;
  28192. if (fastCheck) {
  28193. break;
  28194. }
  28195. }
  28196. }
  28197. return pickingInfo || new BABYLON.PickingInfo();
  28198. };
  28199. /** Launch a ray to try to pick a mesh in the scene
  28200. * @param x position on screen
  28201. * @param y position on screen
  28202. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  28203. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28204. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28205. * @returns a PickingInfo
  28206. */
  28207. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28208. var _this = this;
  28209. if (!BABYLON.PickingInfo) {
  28210. return null;
  28211. }
  28212. var result = this._internalPick(function (world) {
  28213. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28214. return _this._tempPickingRay;
  28215. }, predicate, fastCheck);
  28216. if (result) {
  28217. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28218. }
  28219. return result;
  28220. };
  28221. /** Launch a ray to try to pick a sprite in the scene
  28222. * @param x position on screen
  28223. * @param y position on screen
  28224. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28225. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28226. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28227. * @returns a PickingInfo
  28228. */
  28229. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28230. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28231. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28232. };
  28233. /** Use the given ray to pick a mesh in the scene
  28234. * @param ray The ray to use to pick meshes
  28235. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28236. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28237. * @returns a PickingInfo
  28238. */
  28239. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28240. var _this = this;
  28241. var result = this._internalPick(function (world) {
  28242. if (!_this._pickWithRayInverseMatrix) {
  28243. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28244. }
  28245. world.invertToRef(_this._pickWithRayInverseMatrix);
  28246. if (!_this._cachedRayForTransform) {
  28247. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28248. }
  28249. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28250. return _this._cachedRayForTransform;
  28251. }, predicate, fastCheck);
  28252. if (result) {
  28253. result.ray = ray;
  28254. }
  28255. return result;
  28256. };
  28257. /**
  28258. * Launch a ray to try to pick a mesh in the scene
  28259. * @param x X position on screen
  28260. * @param y Y position on screen
  28261. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  28262. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28263. * @returns an array of PickingInfo
  28264. */
  28265. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28266. var _this = this;
  28267. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28268. };
  28269. /**
  28270. * Launch a ray to try to pick a mesh in the scene
  28271. * @param ray Ray to use
  28272. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
  28273. * @returns an array of PickingInfo
  28274. */
  28275. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28276. var _this = this;
  28277. return this._internalMultiPick(function (world) {
  28278. if (!_this._pickWithRayInverseMatrix) {
  28279. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28280. }
  28281. world.invertToRef(_this._pickWithRayInverseMatrix);
  28282. if (!_this._cachedRayForTransform) {
  28283. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28284. }
  28285. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28286. return _this._cachedRayForTransform;
  28287. }, predicate);
  28288. };
  28289. /**
  28290. * Force the value of meshUnderPointer
  28291. * @param mesh defines the mesh to use
  28292. */
  28293. Scene.prototype.setPointerOverMesh = function (mesh) {
  28294. if (this._pointerOverMesh === mesh) {
  28295. return;
  28296. }
  28297. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28298. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28299. }
  28300. this._pointerOverMesh = mesh;
  28301. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28302. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28303. }
  28304. };
  28305. /**
  28306. * Gets the mesh under the pointer
  28307. * @returns a Mesh or null if no mesh is under the pointer
  28308. */
  28309. Scene.prototype.getPointerOverMesh = function () {
  28310. return this._pointerOverMesh;
  28311. };
  28312. /**
  28313. * Force the sprite under the pointer
  28314. * @param sprite defines the sprite to use
  28315. */
  28316. Scene.prototype.setPointerOverSprite = function (sprite) {
  28317. if (this._pointerOverSprite === sprite) {
  28318. return;
  28319. }
  28320. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28321. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28322. }
  28323. this._pointerOverSprite = sprite;
  28324. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28325. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28326. }
  28327. };
  28328. /**
  28329. * Gets the sprite under the pointer
  28330. * @returns a Sprite or null if no sprite is under the pointer
  28331. */
  28332. Scene.prototype.getPointerOverSprite = function () {
  28333. return this._pointerOverSprite;
  28334. };
  28335. // Physics
  28336. /**
  28337. * Gets the current physics engine
  28338. * @returns a PhysicsEngine or null if none attached
  28339. */
  28340. Scene.prototype.getPhysicsEngine = function () {
  28341. return this._physicsEngine;
  28342. };
  28343. /**
  28344. * Enables physics to the current scene
  28345. * @param gravity defines the scene's gravity for the physics engine
  28346. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28347. * @return a boolean indicating if the physics engine was initialized
  28348. */
  28349. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28350. if (gravity === void 0) { gravity = null; }
  28351. if (this._physicsEngine) {
  28352. return true;
  28353. }
  28354. try {
  28355. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28356. return true;
  28357. }
  28358. catch (e) {
  28359. BABYLON.Tools.Error(e.message);
  28360. return false;
  28361. }
  28362. };
  28363. /**
  28364. * Disables and disposes the physics engine associated with the scene
  28365. */
  28366. Scene.prototype.disablePhysicsEngine = function () {
  28367. if (!this._physicsEngine) {
  28368. return;
  28369. }
  28370. this._physicsEngine.dispose();
  28371. this._physicsEngine = null;
  28372. };
  28373. /**
  28374. * Gets a boolean indicating if there is an active physics engine
  28375. * @returns a boolean indicating if there is an active physics engine
  28376. */
  28377. Scene.prototype.isPhysicsEnabled = function () {
  28378. return this._physicsEngine !== undefined;
  28379. };
  28380. /**
  28381. * Deletes a physics compound impostor
  28382. * @param compound defines the compound to delete
  28383. */
  28384. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28385. var mesh = compound.parts[0].mesh;
  28386. if (mesh.physicsImpostor) {
  28387. mesh.physicsImpostor.dispose( /*true*/);
  28388. mesh.physicsImpostor = null;
  28389. }
  28390. };
  28391. // Misc.
  28392. /** @hidden */
  28393. Scene.prototype._rebuildGeometries = function () {
  28394. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28395. var geometry = _a[_i];
  28396. geometry._rebuild();
  28397. }
  28398. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28399. var mesh = _c[_b];
  28400. mesh._rebuild();
  28401. }
  28402. if (this.postProcessManager) {
  28403. this.postProcessManager._rebuild();
  28404. }
  28405. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28406. var component = _e[_d];
  28407. component.rebuild();
  28408. }
  28409. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28410. var system = _g[_f];
  28411. system.rebuild();
  28412. }
  28413. if (this._postProcessRenderPipelineManager) {
  28414. this._postProcessRenderPipelineManager._rebuild();
  28415. }
  28416. };
  28417. /** @hidden */
  28418. Scene.prototype._rebuildTextures = function () {
  28419. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28420. var texture = _a[_i];
  28421. texture._rebuild();
  28422. }
  28423. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28424. };
  28425. /**
  28426. * Creates a default light for the scene.
  28427. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28428. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28429. */
  28430. Scene.prototype.createDefaultLight = function (replace) {
  28431. if (replace === void 0) { replace = false; }
  28432. // Dispose existing light in replace mode.
  28433. if (replace) {
  28434. if (this.lights) {
  28435. for (var i = 0; i < this.lights.length; i++) {
  28436. this.lights[i].dispose();
  28437. }
  28438. }
  28439. }
  28440. // Light
  28441. if (this.lights.length === 0) {
  28442. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28443. }
  28444. };
  28445. /**
  28446. * Creates a default camera for the scene.
  28447. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28448. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28449. * @param replace has default false, when true replaces the active camera in the scene
  28450. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28451. */
  28452. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28453. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28454. if (replace === void 0) { replace = false; }
  28455. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28456. // Dispose existing camera in replace mode.
  28457. if (replace) {
  28458. if (this.activeCamera) {
  28459. this.activeCamera.dispose();
  28460. this.activeCamera = null;
  28461. }
  28462. }
  28463. // Camera
  28464. if (!this.activeCamera) {
  28465. var worldExtends = this.getWorldExtends();
  28466. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28467. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28468. var camera;
  28469. var radius = worldSize.length() * 1.5;
  28470. // empty scene scenario!
  28471. if (!isFinite(radius)) {
  28472. radius = 1;
  28473. worldCenter.copyFromFloats(0, 0, 0);
  28474. }
  28475. if (createArcRotateCamera) {
  28476. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28477. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28478. arcRotateCamera.wheelPrecision = 100 / radius;
  28479. camera = arcRotateCamera;
  28480. }
  28481. else {
  28482. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28483. freeCamera.setTarget(worldCenter);
  28484. camera = freeCamera;
  28485. }
  28486. camera.minZ = radius * 0.01;
  28487. camera.maxZ = radius * 1000;
  28488. camera.speed = radius * 0.2;
  28489. this.activeCamera = camera;
  28490. var canvas = this.getEngine().getRenderingCanvas();
  28491. if (attachCameraControls && canvas) {
  28492. camera.attachControl(canvas);
  28493. }
  28494. }
  28495. };
  28496. /**
  28497. * Creates a default camera and a default light.
  28498. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28499. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28500. * @param replace has the default false, when true replaces the active camera/light in the scene
  28501. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28502. */
  28503. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28504. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28505. if (replace === void 0) { replace = false; }
  28506. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28507. this.createDefaultLight(replace);
  28508. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28509. };
  28510. /**
  28511. * Creates a new sky box
  28512. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28513. * @param environmentTexture defines the texture to use as environment texture
  28514. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28515. * @param scale defines the overall scale of the skybox
  28516. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28517. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28518. * @returns a new mesh holding the sky box
  28519. */
  28520. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28521. if (pbr === void 0) { pbr = false; }
  28522. if (scale === void 0) { scale = 1000; }
  28523. if (blur === void 0) { blur = 0; }
  28524. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28525. if (!environmentTexture) {
  28526. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28527. return null;
  28528. }
  28529. if (setGlobalEnvTexture) {
  28530. if (environmentTexture) {
  28531. this.environmentTexture = environmentTexture;
  28532. }
  28533. }
  28534. // Skybox
  28535. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28536. if (pbr) {
  28537. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28538. hdrSkyboxMaterial.backFaceCulling = false;
  28539. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28540. if (hdrSkyboxMaterial.reflectionTexture) {
  28541. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28542. }
  28543. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28544. hdrSkyboxMaterial.disableLighting = true;
  28545. hdrSkyboxMaterial.twoSidedLighting = true;
  28546. hdrSkybox.infiniteDistance = true;
  28547. hdrSkybox.material = hdrSkyboxMaterial;
  28548. }
  28549. else {
  28550. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28551. skyboxMaterial.backFaceCulling = false;
  28552. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28553. if (skyboxMaterial.reflectionTexture) {
  28554. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28555. }
  28556. skyboxMaterial.disableLighting = true;
  28557. hdrSkybox.infiniteDistance = true;
  28558. hdrSkybox.material = skyboxMaterial;
  28559. }
  28560. return hdrSkybox;
  28561. };
  28562. /**
  28563. * Creates a new environment
  28564. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28565. * @param options defines the options you can use to configure the environment
  28566. * @returns the new EnvironmentHelper
  28567. */
  28568. Scene.prototype.createDefaultEnvironment = function (options) {
  28569. if (BABYLON.EnvironmentHelper) {
  28570. return new BABYLON.EnvironmentHelper(options, this);
  28571. }
  28572. return null;
  28573. };
  28574. /**
  28575. * Creates a new VREXperienceHelper
  28576. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28577. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28578. * @returns a new VREXperienceHelper
  28579. */
  28580. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28581. if (webVROptions === void 0) { webVROptions = {}; }
  28582. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28583. };
  28584. // Tags
  28585. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28586. if (tagsQuery === undefined) {
  28587. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28588. return list;
  28589. }
  28590. var listByTags = [];
  28591. forEach = forEach || (function (item) { return; });
  28592. for (var i in list) {
  28593. var item = list[i];
  28594. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28595. listByTags.push(item);
  28596. forEach(item);
  28597. }
  28598. }
  28599. return listByTags;
  28600. };
  28601. /**
  28602. * Get a list of meshes by tags
  28603. * @param tagsQuery defines the tags query to use
  28604. * @param forEach defines a predicate used to filter results
  28605. * @returns an array of Mesh
  28606. */
  28607. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28608. return this._getByTags(this.meshes, tagsQuery, forEach);
  28609. };
  28610. /**
  28611. * Get a list of cameras by tags
  28612. * @param tagsQuery defines the tags query to use
  28613. * @param forEach defines a predicate used to filter results
  28614. * @returns an array of Camera
  28615. */
  28616. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28617. return this._getByTags(this.cameras, tagsQuery, forEach);
  28618. };
  28619. /**
  28620. * Get a list of lights by tags
  28621. * @param tagsQuery defines the tags query to use
  28622. * @param forEach defines a predicate used to filter results
  28623. * @returns an array of Light
  28624. */
  28625. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28626. return this._getByTags(this.lights, tagsQuery, forEach);
  28627. };
  28628. /**
  28629. * Get a list of materials by tags
  28630. * @param tagsQuery defines the tags query to use
  28631. * @param forEach defines a predicate used to filter results
  28632. * @returns an array of Material
  28633. */
  28634. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28635. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28636. };
  28637. /**
  28638. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28639. * This allowed control for front to back rendering or reversly depending of the special needs.
  28640. *
  28641. * @param renderingGroupId The rendering group id corresponding to its index
  28642. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28643. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28644. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28645. */
  28646. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28647. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28648. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28649. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28650. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28651. };
  28652. /**
  28653. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28654. *
  28655. * @param renderingGroupId The rendering group id corresponding to its index
  28656. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28657. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28658. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28659. */
  28660. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28661. if (depth === void 0) { depth = true; }
  28662. if (stencil === void 0) { stencil = true; }
  28663. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28664. };
  28665. /**
  28666. * Gets the current auto clear configuration for one rendering group of the rendering
  28667. * manager.
  28668. * @param index the rendering group index to get the information for
  28669. * @returns The auto clear setup for the requested rendering group
  28670. */
  28671. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28672. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28673. };
  28674. /**
  28675. * Will flag all materials as dirty to trigger new shader compilation
  28676. * @param flag defines the flag used to specify which material part must be marked as dirty
  28677. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28678. */
  28679. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28680. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28681. var material = _a[_i];
  28682. if (predicate && !predicate(material)) {
  28683. continue;
  28684. }
  28685. material.markAsDirty(flag);
  28686. }
  28687. };
  28688. /** @hidden */
  28689. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28690. var _this = this;
  28691. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28692. this._activeRequests.push(request);
  28693. request.onCompleteObservable.add(function (request) {
  28694. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28695. });
  28696. return request;
  28697. };
  28698. /** @hidden */
  28699. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28700. var _this = this;
  28701. return new Promise(function (resolve, reject) {
  28702. _this._loadFile(url, function (data) {
  28703. resolve(data);
  28704. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28705. reject(exception);
  28706. });
  28707. });
  28708. };
  28709. // Statics
  28710. Scene._FOGMODE_NONE = 0;
  28711. Scene._FOGMODE_EXP = 1;
  28712. Scene._FOGMODE_EXP2 = 2;
  28713. Scene._FOGMODE_LINEAR = 3;
  28714. Scene._uniqueIdCounter = 0;
  28715. /**
  28716. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28717. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28718. */
  28719. Scene.MinDeltaTime = 1.0;
  28720. /**
  28721. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28722. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28723. */
  28724. Scene.MaxDeltaTime = 1000.0;
  28725. /** The distance in pixel that you have to move to prevent some events */
  28726. Scene.DragMovementThreshold = 10; // in pixels
  28727. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28728. Scene.LongPressDelay = 500; // in milliseconds
  28729. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28730. Scene.DoubleClickDelay = 300; // in milliseconds
  28731. /** If you need to check double click without raising a single click at first click, enable this flag */
  28732. Scene.ExclusiveDoubleClickMode = false;
  28733. return Scene;
  28734. }(BABYLON.AbstractScene));
  28735. BABYLON.Scene = Scene;
  28736. })(BABYLON || (BABYLON = {}));
  28737. //# sourceMappingURL=babylon.scene.js.map
  28738. var BABYLON;
  28739. (function (BABYLON) {
  28740. /**
  28741. * Set of assets to keep when moving a scene into an asset container.
  28742. */
  28743. var KeepAssets = /** @class */ (function (_super) {
  28744. __extends(KeepAssets, _super);
  28745. function KeepAssets() {
  28746. return _super !== null && _super.apply(this, arguments) || this;
  28747. }
  28748. return KeepAssets;
  28749. }(BABYLON.AbstractScene));
  28750. BABYLON.KeepAssets = KeepAssets;
  28751. /**
  28752. * Container with a set of assets that can be added or removed from a scene.
  28753. */
  28754. var AssetContainer = /** @class */ (function (_super) {
  28755. __extends(AssetContainer, _super);
  28756. /**
  28757. * Instantiates an AssetContainer.
  28758. * @param scene The scene the AssetContainer belongs to.
  28759. */
  28760. function AssetContainer(scene) {
  28761. var _this = _super.call(this) || this;
  28762. _this.scene = scene;
  28763. return _this;
  28764. }
  28765. /**
  28766. * Adds all the assets from the container to the scene.
  28767. */
  28768. AssetContainer.prototype.addAllToScene = function () {
  28769. var _this = this;
  28770. this.cameras.forEach(function (o) {
  28771. _this.scene.addCamera(o);
  28772. });
  28773. this.lights.forEach(function (o) {
  28774. _this.scene.addLight(o);
  28775. });
  28776. this.meshes.forEach(function (o) {
  28777. _this.scene.addMesh(o);
  28778. });
  28779. this.skeletons.forEach(function (o) {
  28780. _this.scene.addSkeleton(o);
  28781. });
  28782. this.animations.forEach(function (o) {
  28783. _this.scene.addAnimation(o);
  28784. });
  28785. this.animationGroups.forEach(function (o) {
  28786. _this.scene.addAnimationGroup(o);
  28787. });
  28788. this.multiMaterials.forEach(function (o) {
  28789. _this.scene.addMultiMaterial(o);
  28790. });
  28791. this.materials.forEach(function (o) {
  28792. _this.scene.addMaterial(o);
  28793. });
  28794. this.morphTargetManagers.forEach(function (o) {
  28795. _this.scene.addMorphTargetManager(o);
  28796. });
  28797. this.geometries.forEach(function (o) {
  28798. _this.scene.addGeometry(o);
  28799. });
  28800. this.transformNodes.forEach(function (o) {
  28801. _this.scene.addTransformNode(o);
  28802. });
  28803. this.actionManagers.forEach(function (o) {
  28804. _this.scene.addActionManager(o);
  28805. });
  28806. this.sounds.forEach(function (o) {
  28807. o.play();
  28808. o.autoplay = true;
  28809. _this.scene.mainSoundTrack.AddSound(o);
  28810. });
  28811. this.textures.forEach(function (o) {
  28812. _this.scene.addTexture(o);
  28813. });
  28814. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28815. var component = _a[_i];
  28816. component.addFromContainer(this.scene);
  28817. }
  28818. };
  28819. /**
  28820. * Removes all the assets in the container from the scene
  28821. */
  28822. AssetContainer.prototype.removeAllFromScene = function () {
  28823. var _this = this;
  28824. this.cameras.forEach(function (o) {
  28825. _this.scene.removeCamera(o);
  28826. });
  28827. this.lights.forEach(function (o) {
  28828. _this.scene.removeLight(o);
  28829. });
  28830. this.meshes.forEach(function (o) {
  28831. _this.scene.removeMesh(o);
  28832. });
  28833. this.skeletons.forEach(function (o) {
  28834. _this.scene.removeSkeleton(o);
  28835. });
  28836. this.animations.forEach(function (o) {
  28837. _this.scene.removeAnimation(o);
  28838. });
  28839. this.animationGroups.forEach(function (o) {
  28840. _this.scene.removeAnimationGroup(o);
  28841. });
  28842. this.multiMaterials.forEach(function (o) {
  28843. _this.scene.removeMultiMaterial(o);
  28844. });
  28845. this.materials.forEach(function (o) {
  28846. _this.scene.removeMaterial(o);
  28847. });
  28848. this.morphTargetManagers.forEach(function (o) {
  28849. _this.scene.removeMorphTargetManager(o);
  28850. });
  28851. this.geometries.forEach(function (o) {
  28852. _this.scene.removeGeometry(o);
  28853. });
  28854. this.transformNodes.forEach(function (o) {
  28855. _this.scene.removeTransformNode(o);
  28856. });
  28857. this.actionManagers.forEach(function (o) {
  28858. _this.scene.removeActionManager(o);
  28859. });
  28860. this.sounds.forEach(function (o) {
  28861. o.stop();
  28862. o.autoplay = false;
  28863. _this.scene.mainSoundTrack.RemoveSound(o);
  28864. });
  28865. this.textures.forEach(function (o) {
  28866. _this.scene.removeTexture(o);
  28867. });
  28868. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28869. var component = _a[_i];
  28870. component.removeFromContainer(this.scene);
  28871. }
  28872. };
  28873. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28874. if (!sourceAssets) {
  28875. return;
  28876. }
  28877. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28878. var asset = sourceAssets_1[_i];
  28879. var move = true;
  28880. if (keepAssets) {
  28881. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28882. var keepAsset = keepAssets_1[_a];
  28883. if (asset === keepAsset) {
  28884. move = false;
  28885. break;
  28886. }
  28887. }
  28888. }
  28889. if (move) {
  28890. targetAssets.push(asset);
  28891. }
  28892. }
  28893. };
  28894. /**
  28895. * Removes all the assets contained in the scene and adds them to the container.
  28896. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28897. */
  28898. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28899. if (keepAssets === undefined) {
  28900. keepAssets = new KeepAssets();
  28901. }
  28902. for (var key in this) {
  28903. if (this.hasOwnProperty(key)) {
  28904. this[key] = this[key] || [];
  28905. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28906. }
  28907. }
  28908. this.removeAllFromScene();
  28909. };
  28910. /**
  28911. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  28912. * @returns the root mesh
  28913. */
  28914. AssetContainer.prototype.createRootMesh = function () {
  28915. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28916. this.meshes.forEach(function (m) {
  28917. if (!m.parent) {
  28918. rootMesh.addChild(m);
  28919. }
  28920. });
  28921. this.meshes.unshift(rootMesh);
  28922. return rootMesh;
  28923. };
  28924. return AssetContainer;
  28925. }(BABYLON.AbstractScene));
  28926. BABYLON.AssetContainer = AssetContainer;
  28927. })(BABYLON || (BABYLON = {}));
  28928. //# sourceMappingURL=babylon.assetContainer.js.map
  28929. var BABYLON;
  28930. (function (BABYLON) {
  28931. var Buffer = /** @class */ (function () {
  28932. /**
  28933. * Constructor
  28934. * @param engine the engine
  28935. * @param data the data to use for this buffer
  28936. * @param updatable whether the data is updatable
  28937. * @param stride the stride (optional)
  28938. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28939. * @param instanced whether the buffer is instanced (optional)
  28940. * @param useBytes set to true if the stride in in bytes (optional)
  28941. */
  28942. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28943. if (stride === void 0) { stride = 0; }
  28944. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28945. if (instanced === void 0) { instanced = false; }
  28946. if (useBytes === void 0) { useBytes = false; }
  28947. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28948. this._engine = engine.getScene().getEngine();
  28949. }
  28950. else {
  28951. this._engine = engine;
  28952. }
  28953. this._updatable = updatable;
  28954. this._instanced = instanced;
  28955. this._data = data;
  28956. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28957. if (!postponeInternalCreation) { // by default
  28958. this.create();
  28959. }
  28960. }
  28961. /**
  28962. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28963. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28964. * @param offset defines offset in the buffer (0 by default)
  28965. * @param size defines the size in floats of attributes (position is 3 for instance)
  28966. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28967. * @param instanced defines if the vertex buffer contains indexed data
  28968. * @param useBytes defines if the offset and stride are in bytes
  28969. * @returns the new vertex buffer
  28970. */
  28971. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28972. if (useBytes === void 0) { useBytes = false; }
  28973. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28974. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28975. // a lot of these parameters are ignored as they are overriden by the buffer
  28976. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28977. };
  28978. // Properties
  28979. Buffer.prototype.isUpdatable = function () {
  28980. return this._updatable;
  28981. };
  28982. Buffer.prototype.getData = function () {
  28983. return this._data;
  28984. };
  28985. Buffer.prototype.getBuffer = function () {
  28986. return this._buffer;
  28987. };
  28988. /**
  28989. * Gets the stride in float32 units (i.e. byte stride / 4).
  28990. * May not be an integer if the byte stride is not divisible by 4.
  28991. * DEPRECATED. Use byteStride instead.
  28992. * @returns the stride in float32 units
  28993. */
  28994. Buffer.prototype.getStrideSize = function () {
  28995. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28996. };
  28997. // Methods
  28998. Buffer.prototype.create = function (data) {
  28999. if (data === void 0) { data = null; }
  29000. if (!data && this._buffer) {
  29001. return; // nothing to do
  29002. }
  29003. data = data || this._data;
  29004. if (!data) {
  29005. return;
  29006. }
  29007. if (!this._buffer) { // create buffer
  29008. if (this._updatable) {
  29009. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29010. this._data = data;
  29011. }
  29012. else {
  29013. this._buffer = this._engine.createVertexBuffer(data);
  29014. }
  29015. }
  29016. else if (this._updatable) { // update buffer
  29017. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29018. this._data = data;
  29019. }
  29020. };
  29021. Buffer.prototype._rebuild = function () {
  29022. this._buffer = null;
  29023. this.create(this._data);
  29024. };
  29025. Buffer.prototype.update = function (data) {
  29026. this.create(data);
  29027. };
  29028. /**
  29029. * Updates the data directly.
  29030. * @param data the new data
  29031. * @param offset the new offset
  29032. * @param vertexCount the vertex count (optional)
  29033. * @param useBytes set to true if the offset is in bytes
  29034. */
  29035. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29036. if (useBytes === void 0) { useBytes = false; }
  29037. if (!this._buffer) {
  29038. return;
  29039. }
  29040. if (this._updatable) { // update buffer
  29041. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29042. this._data = null;
  29043. }
  29044. };
  29045. Buffer.prototype.dispose = function () {
  29046. if (!this._buffer) {
  29047. return;
  29048. }
  29049. if (this._engine._releaseBuffer(this._buffer)) {
  29050. this._buffer = null;
  29051. }
  29052. };
  29053. return Buffer;
  29054. }());
  29055. BABYLON.Buffer = Buffer;
  29056. })(BABYLON || (BABYLON = {}));
  29057. //# sourceMappingURL=babylon.buffer.js.map
  29058. var BABYLON;
  29059. (function (BABYLON) {
  29060. var VertexBuffer = /** @class */ (function () {
  29061. /**
  29062. * Constructor
  29063. * @param engine the engine
  29064. * @param data the data to use for this vertex buffer
  29065. * @param kind the vertex buffer kind
  29066. * @param updatable whether the data is updatable
  29067. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29068. * @param stride the stride (optional)
  29069. * @param instanced whether the buffer is instanced (optional)
  29070. * @param offset the offset of the data (optional)
  29071. * @param size the number of components (optional)
  29072. * @param type the type of the component (optional)
  29073. * @param normalized whether the data contains normalized data (optional)
  29074. * @param useBytes set to true if stride and offset are in bytes (optional)
  29075. */
  29076. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29077. if (normalized === void 0) { normalized = false; }
  29078. if (useBytes === void 0) { useBytes = false; }
  29079. if (data instanceof BABYLON.Buffer) {
  29080. this._buffer = data;
  29081. this._ownsBuffer = false;
  29082. }
  29083. else {
  29084. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29085. this._ownsBuffer = true;
  29086. }
  29087. this._kind = kind;
  29088. if (type == undefined) {
  29089. var data_1 = this.getData();
  29090. this.type = VertexBuffer.FLOAT;
  29091. if (data_1 instanceof Int8Array)
  29092. this.type = VertexBuffer.BYTE;
  29093. else if (data_1 instanceof Uint8Array)
  29094. this.type = VertexBuffer.UNSIGNED_BYTE;
  29095. else if (data_1 instanceof Int16Array)
  29096. this.type = VertexBuffer.SHORT;
  29097. else if (data_1 instanceof Uint16Array)
  29098. this.type = VertexBuffer.UNSIGNED_SHORT;
  29099. else if (data_1 instanceof Int32Array)
  29100. this.type = VertexBuffer.INT;
  29101. else if (data_1 instanceof Uint32Array)
  29102. this.type = VertexBuffer.UNSIGNED_INT;
  29103. }
  29104. else {
  29105. this.type = type;
  29106. }
  29107. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29108. if (useBytes) {
  29109. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29110. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29111. this.byteOffset = offset || 0;
  29112. }
  29113. else {
  29114. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29115. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29116. this.byteOffset = (offset || 0) * typeByteLength;
  29117. }
  29118. this.normalized = normalized;
  29119. this._instanced = instanced !== undefined ? instanced : false;
  29120. this._instanceDivisor = instanced ? 1 : 0;
  29121. }
  29122. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29123. /**
  29124. * Gets or sets the instance divisor when in instanced mode
  29125. */
  29126. get: function () {
  29127. return this._instanceDivisor;
  29128. },
  29129. set: function (value) {
  29130. this._instanceDivisor = value;
  29131. if (value == 0) {
  29132. this._instanced = false;
  29133. }
  29134. else {
  29135. this._instanced = true;
  29136. }
  29137. },
  29138. enumerable: true,
  29139. configurable: true
  29140. });
  29141. VertexBuffer.prototype._rebuild = function () {
  29142. if (!this._buffer) {
  29143. return;
  29144. }
  29145. this._buffer._rebuild();
  29146. };
  29147. /**
  29148. * Returns the kind of the VertexBuffer (string).
  29149. */
  29150. VertexBuffer.prototype.getKind = function () {
  29151. return this._kind;
  29152. };
  29153. // Properties
  29154. /**
  29155. * Boolean : is the VertexBuffer updatable ?
  29156. */
  29157. VertexBuffer.prototype.isUpdatable = function () {
  29158. return this._buffer.isUpdatable();
  29159. };
  29160. /**
  29161. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29162. */
  29163. VertexBuffer.prototype.getData = function () {
  29164. return this._buffer.getData();
  29165. };
  29166. /**
  29167. * Returns the WebGLBuffer associated to the VertexBuffer.
  29168. */
  29169. VertexBuffer.prototype.getBuffer = function () {
  29170. return this._buffer.getBuffer();
  29171. };
  29172. /**
  29173. * Returns the stride as a multiple of the type byte length.
  29174. * DEPRECATED. Use byteStride instead.
  29175. */
  29176. VertexBuffer.prototype.getStrideSize = function () {
  29177. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29178. };
  29179. /**
  29180. * Returns the offset as a multiple of the type byte length.
  29181. * DEPRECATED. Use byteOffset instead.
  29182. */
  29183. VertexBuffer.prototype.getOffset = function () {
  29184. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29185. };
  29186. /**
  29187. * Returns the number of components per vertex attribute (integer).
  29188. */
  29189. VertexBuffer.prototype.getSize = function () {
  29190. return this._size;
  29191. };
  29192. /**
  29193. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29194. */
  29195. VertexBuffer.prototype.getIsInstanced = function () {
  29196. return this._instanced;
  29197. };
  29198. /**
  29199. * Returns the instancing divisor, zero for non-instanced (integer).
  29200. */
  29201. VertexBuffer.prototype.getInstanceDivisor = function () {
  29202. return this._instanceDivisor;
  29203. };
  29204. // Methods
  29205. /**
  29206. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29207. * Returns the created WebGLBuffer.
  29208. */
  29209. VertexBuffer.prototype.create = function (data) {
  29210. return this._buffer.create(data);
  29211. };
  29212. /**
  29213. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29214. * This function will create a new buffer if the current one is not updatable
  29215. * Returns the updated WebGLBuffer.
  29216. */
  29217. VertexBuffer.prototype.update = function (data) {
  29218. return this._buffer.update(data);
  29219. };
  29220. /**
  29221. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29222. * Returns the directly updated WebGLBuffer.
  29223. * @param data the new data
  29224. * @param offset the new offset
  29225. * @param useBytes set to true if the offset is in bytes
  29226. */
  29227. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29228. if (useBytes === void 0) { useBytes = false; }
  29229. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29230. };
  29231. /**
  29232. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29233. */
  29234. VertexBuffer.prototype.dispose = function () {
  29235. if (this._ownsBuffer) {
  29236. this._buffer.dispose();
  29237. }
  29238. };
  29239. /**
  29240. * Enumerates each value of this vertex buffer as numbers.
  29241. * @param count the number of values to enumerate
  29242. * @param callback the callback function called for each value
  29243. */
  29244. VertexBuffer.prototype.forEach = function (count, callback) {
  29245. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29246. };
  29247. Object.defineProperty(VertexBuffer, "PositionKind", {
  29248. get: function () {
  29249. return VertexBuffer._PositionKind;
  29250. },
  29251. enumerable: true,
  29252. configurable: true
  29253. });
  29254. Object.defineProperty(VertexBuffer, "NormalKind", {
  29255. get: function () {
  29256. return VertexBuffer._NormalKind;
  29257. },
  29258. enumerable: true,
  29259. configurable: true
  29260. });
  29261. Object.defineProperty(VertexBuffer, "TangentKind", {
  29262. get: function () {
  29263. return VertexBuffer._TangentKind;
  29264. },
  29265. enumerable: true,
  29266. configurable: true
  29267. });
  29268. Object.defineProperty(VertexBuffer, "UVKind", {
  29269. get: function () {
  29270. return VertexBuffer._UVKind;
  29271. },
  29272. enumerable: true,
  29273. configurable: true
  29274. });
  29275. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29276. get: function () {
  29277. return VertexBuffer._UV2Kind;
  29278. },
  29279. enumerable: true,
  29280. configurable: true
  29281. });
  29282. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29283. get: function () {
  29284. return VertexBuffer._UV3Kind;
  29285. },
  29286. enumerable: true,
  29287. configurable: true
  29288. });
  29289. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29290. get: function () {
  29291. return VertexBuffer._UV4Kind;
  29292. },
  29293. enumerable: true,
  29294. configurable: true
  29295. });
  29296. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29297. get: function () {
  29298. return VertexBuffer._UV5Kind;
  29299. },
  29300. enumerable: true,
  29301. configurable: true
  29302. });
  29303. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29304. get: function () {
  29305. return VertexBuffer._UV6Kind;
  29306. },
  29307. enumerable: true,
  29308. configurable: true
  29309. });
  29310. Object.defineProperty(VertexBuffer, "ColorKind", {
  29311. get: function () {
  29312. return VertexBuffer._ColorKind;
  29313. },
  29314. enumerable: true,
  29315. configurable: true
  29316. });
  29317. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29318. get: function () {
  29319. return VertexBuffer._MatricesIndicesKind;
  29320. },
  29321. enumerable: true,
  29322. configurable: true
  29323. });
  29324. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29325. get: function () {
  29326. return VertexBuffer._MatricesWeightsKind;
  29327. },
  29328. enumerable: true,
  29329. configurable: true
  29330. });
  29331. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29332. get: function () {
  29333. return VertexBuffer._MatricesIndicesExtraKind;
  29334. },
  29335. enumerable: true,
  29336. configurable: true
  29337. });
  29338. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29339. get: function () {
  29340. return VertexBuffer._MatricesWeightsExtraKind;
  29341. },
  29342. enumerable: true,
  29343. configurable: true
  29344. });
  29345. /**
  29346. * Deduces the stride given a kind.
  29347. * @param kind The kind string to deduce
  29348. * @returns The deduced stride
  29349. */
  29350. VertexBuffer.DeduceStride = function (kind) {
  29351. switch (kind) {
  29352. case VertexBuffer.UVKind:
  29353. case VertexBuffer.UV2Kind:
  29354. case VertexBuffer.UV3Kind:
  29355. case VertexBuffer.UV4Kind:
  29356. case VertexBuffer.UV5Kind:
  29357. case VertexBuffer.UV6Kind:
  29358. return 2;
  29359. case VertexBuffer.NormalKind:
  29360. case VertexBuffer.PositionKind:
  29361. return 3;
  29362. case VertexBuffer.ColorKind:
  29363. case VertexBuffer.MatricesIndicesKind:
  29364. case VertexBuffer.MatricesIndicesExtraKind:
  29365. case VertexBuffer.MatricesWeightsKind:
  29366. case VertexBuffer.MatricesWeightsExtraKind:
  29367. case VertexBuffer.TangentKind:
  29368. return 4;
  29369. default:
  29370. throw new Error("Invalid kind '" + kind + "'");
  29371. }
  29372. };
  29373. /**
  29374. * Gets the byte length of the given type.
  29375. * @param type the type
  29376. * @returns the number of bytes
  29377. */
  29378. VertexBuffer.GetTypeByteLength = function (type) {
  29379. switch (type) {
  29380. case VertexBuffer.BYTE:
  29381. case VertexBuffer.UNSIGNED_BYTE:
  29382. return 1;
  29383. case VertexBuffer.SHORT:
  29384. case VertexBuffer.UNSIGNED_SHORT:
  29385. return 2;
  29386. case VertexBuffer.INT:
  29387. case VertexBuffer.FLOAT:
  29388. return 4;
  29389. default:
  29390. throw new Error("Invalid type '" + type + "'");
  29391. }
  29392. };
  29393. /**
  29394. * Enumerates each value of the given parameters as numbers.
  29395. * @param data the data to enumerate
  29396. * @param byteOffset the byte offset of the data
  29397. * @param byteStride the byte stride of the data
  29398. * @param componentCount the number of components per element
  29399. * @param componentType the type of the component
  29400. * @param count the total number of components
  29401. * @param normalized whether the data is normalized
  29402. * @param callback the callback function called for each value
  29403. */
  29404. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29405. if (data instanceof Array) {
  29406. var offset = byteOffset / 4;
  29407. var stride = byteStride / 4;
  29408. for (var index = 0; index < count; index += componentCount) {
  29409. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29410. callback(data[offset + componentIndex], index + componentIndex);
  29411. }
  29412. offset += stride;
  29413. }
  29414. }
  29415. else {
  29416. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29417. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29418. for (var index = 0; index < count; index += componentCount) {
  29419. var componentByteOffset = byteOffset;
  29420. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29421. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29422. callback(value, index + componentIndex);
  29423. componentByteOffset += componentByteLength;
  29424. }
  29425. byteOffset += byteStride;
  29426. }
  29427. }
  29428. };
  29429. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29430. switch (type) {
  29431. case VertexBuffer.BYTE: {
  29432. var value = dataView.getInt8(byteOffset);
  29433. if (normalized) {
  29434. value = Math.max(value / 127, -1);
  29435. }
  29436. return value;
  29437. }
  29438. case VertexBuffer.UNSIGNED_BYTE: {
  29439. var value = dataView.getUint8(byteOffset);
  29440. if (normalized) {
  29441. value = value / 255;
  29442. }
  29443. return value;
  29444. }
  29445. case VertexBuffer.SHORT: {
  29446. var value = dataView.getInt16(byteOffset, true);
  29447. if (normalized) {
  29448. value = Math.max(value / 16383, -1);
  29449. }
  29450. return value;
  29451. }
  29452. case VertexBuffer.UNSIGNED_SHORT: {
  29453. var value = dataView.getUint16(byteOffset, true);
  29454. if (normalized) {
  29455. value = value / 65535;
  29456. }
  29457. return value;
  29458. }
  29459. case VertexBuffer.FLOAT: {
  29460. return dataView.getFloat32(byteOffset, true);
  29461. }
  29462. default: {
  29463. throw new Error("Invalid component type " + type);
  29464. }
  29465. }
  29466. };
  29467. /**
  29468. * The byte type.
  29469. */
  29470. VertexBuffer.BYTE = 5120;
  29471. /**
  29472. * The unsigned byte type.
  29473. */
  29474. VertexBuffer.UNSIGNED_BYTE = 5121;
  29475. /**
  29476. * The short type.
  29477. */
  29478. VertexBuffer.SHORT = 5122;
  29479. /**
  29480. * The unsigned short type.
  29481. */
  29482. VertexBuffer.UNSIGNED_SHORT = 5123;
  29483. /**
  29484. * The integer type.
  29485. */
  29486. VertexBuffer.INT = 5124;
  29487. /**
  29488. * The unsigned integer type.
  29489. */
  29490. VertexBuffer.UNSIGNED_INT = 5125;
  29491. /**
  29492. * The float type.
  29493. */
  29494. VertexBuffer.FLOAT = 5126;
  29495. // Enums
  29496. VertexBuffer._PositionKind = "position";
  29497. VertexBuffer._NormalKind = "normal";
  29498. VertexBuffer._TangentKind = "tangent";
  29499. VertexBuffer._UVKind = "uv";
  29500. VertexBuffer._UV2Kind = "uv2";
  29501. VertexBuffer._UV3Kind = "uv3";
  29502. VertexBuffer._UV4Kind = "uv4";
  29503. VertexBuffer._UV5Kind = "uv5";
  29504. VertexBuffer._UV6Kind = "uv6";
  29505. VertexBuffer._ColorKind = "color";
  29506. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29507. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29508. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29509. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29510. return VertexBuffer;
  29511. }());
  29512. BABYLON.VertexBuffer = VertexBuffer;
  29513. })(BABYLON || (BABYLON = {}));
  29514. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29515. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29516. var BABYLON;
  29517. (function (BABYLON) {
  29518. /**
  29519. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29520. */
  29521. var DummyInternalTextureTracker = /** @class */ (function () {
  29522. function DummyInternalTextureTracker() {
  29523. /**
  29524. * Gets or set the previous tracker in the list
  29525. */
  29526. this.previous = null;
  29527. /**
  29528. * Gets or set the next tracker in the list
  29529. */
  29530. this.next = null;
  29531. }
  29532. return DummyInternalTextureTracker;
  29533. }());
  29534. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29535. })(BABYLON || (BABYLON = {}));
  29536. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29537. var BABYLON;
  29538. (function (BABYLON) {
  29539. /**
  29540. * Class used to store data associated with WebGL texture data for the engine
  29541. * This class should not be used directly
  29542. */
  29543. var InternalTexture = /** @class */ (function () {
  29544. /**
  29545. * Creates a new InternalTexture
  29546. * @param engine defines the engine to use
  29547. * @param dataSource defines the type of data that will be used
  29548. */
  29549. function InternalTexture(engine, dataSource) {
  29550. /**
  29551. * Observable called when the texture is loaded
  29552. */
  29553. this.onLoadedObservable = new BABYLON.Observable();
  29554. /**
  29555. * Gets or set the previous tracker in the list
  29556. */
  29557. this.previous = null;
  29558. /**
  29559. * Gets or set the next tracker in the list
  29560. */
  29561. this.next = null;
  29562. // Private
  29563. /** @hidden */
  29564. this._initialSlot = -1;
  29565. /** @hidden */
  29566. this._designatedSlot = -1;
  29567. /** @hidden */
  29568. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29569. /** @hidden */
  29570. this._comparisonFunction = 0;
  29571. /** @hidden */
  29572. this._sphericalPolynomial = null;
  29573. /** @hidden */
  29574. this._lodGenerationScale = 0;
  29575. /** @hidden */
  29576. this._lodGenerationOffset = 0;
  29577. /** @hidden */
  29578. this._isRGBD = false;
  29579. /** @hidden */
  29580. this._references = 1;
  29581. this._engine = engine;
  29582. this._dataSource = dataSource;
  29583. this._webGLTexture = engine._createTexture();
  29584. }
  29585. /**
  29586. * Gets the Engine the texture belongs to.
  29587. * @returns The babylon engine
  29588. */
  29589. InternalTexture.prototype.getEngine = function () {
  29590. return this._engine;
  29591. };
  29592. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29593. /**
  29594. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29595. */
  29596. get: function () {
  29597. return this._dataSource;
  29598. },
  29599. enumerable: true,
  29600. configurable: true
  29601. });
  29602. /**
  29603. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29604. */
  29605. InternalTexture.prototype.incrementReferences = function () {
  29606. this._references++;
  29607. };
  29608. /**
  29609. * Change the size of the texture (not the size of the content)
  29610. * @param width defines the new width
  29611. * @param height defines the new height
  29612. * @param depth defines the new depth (1 by default)
  29613. */
  29614. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29615. if (depth === void 0) { depth = 1; }
  29616. this.width = width;
  29617. this.height = height;
  29618. this.depth = depth;
  29619. this.baseWidth = width;
  29620. this.baseHeight = height;
  29621. this.baseDepth = depth;
  29622. this._size = width * height * depth;
  29623. };
  29624. /** @hidden */
  29625. InternalTexture.prototype._rebuild = function () {
  29626. var _this = this;
  29627. var proxy;
  29628. this.isReady = false;
  29629. this._cachedCoordinatesMode = null;
  29630. this._cachedWrapU = null;
  29631. this._cachedWrapV = null;
  29632. this._cachedAnisotropicFilteringLevel = null;
  29633. switch (this._dataSource) {
  29634. case InternalTexture.DATASOURCE_TEMP:
  29635. return;
  29636. case InternalTexture.DATASOURCE_URL:
  29637. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29638. _this.isReady = true;
  29639. }, null, this._buffer, undefined, this.format);
  29640. proxy._swapAndDie(this);
  29641. return;
  29642. case InternalTexture.DATASOURCE_RAW:
  29643. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29644. proxy._swapAndDie(this);
  29645. this.isReady = true;
  29646. return;
  29647. case InternalTexture.DATASOURCE_RAW3D:
  29648. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29649. proxy._swapAndDie(this);
  29650. this.isReady = true;
  29651. return;
  29652. case InternalTexture.DATASOURCE_DYNAMIC:
  29653. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29654. proxy._swapAndDie(this);
  29655. // The engine will make sure to update content so no need to flag it as isReady = true
  29656. return;
  29657. case InternalTexture.DATASOURCE_RENDERTARGET:
  29658. var options = new BABYLON.RenderTargetCreationOptions();
  29659. options.generateDepthBuffer = this._generateDepthBuffer;
  29660. options.generateMipMaps = this.generateMipMaps;
  29661. options.generateStencilBuffer = this._generateStencilBuffer;
  29662. options.samplingMode = this.samplingMode;
  29663. options.type = this.type;
  29664. if (this.isCube) {
  29665. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29666. }
  29667. else {
  29668. var size = {
  29669. width: this.width,
  29670. height: this.height
  29671. };
  29672. proxy = this._engine.createRenderTargetTexture(size, options);
  29673. }
  29674. proxy._swapAndDie(this);
  29675. this.isReady = true;
  29676. return;
  29677. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29678. var depthTextureOptions = {
  29679. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29680. comparisonFunction: this._comparisonFunction,
  29681. generateStencil: this._generateStencilBuffer,
  29682. isCube: this.isCube
  29683. };
  29684. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29685. proxy._swapAndDie(this);
  29686. this.isReady = true;
  29687. return;
  29688. case InternalTexture.DATASOURCE_CUBE:
  29689. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29690. _this.isReady = true;
  29691. }, null, this.format, this._extension);
  29692. proxy._swapAndDie(this);
  29693. return;
  29694. case InternalTexture.DATASOURCE_CUBERAW:
  29695. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29696. proxy._swapAndDie(this);
  29697. this.isReady = true;
  29698. return;
  29699. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29700. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29701. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29702. _this.isReady = true;
  29703. });
  29704. proxy._swapAndDie(this);
  29705. return;
  29706. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29707. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29708. if (proxy) {
  29709. proxy._swapAndDie(_this);
  29710. }
  29711. _this.isReady = true;
  29712. }, null, this.format, this._extension);
  29713. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29714. return;
  29715. }
  29716. };
  29717. InternalTexture.prototype._swapAndDie = function (target) {
  29718. target._webGLTexture = this._webGLTexture;
  29719. if (this._framebuffer) {
  29720. target._framebuffer = this._framebuffer;
  29721. }
  29722. if (this._depthStencilBuffer) {
  29723. target._depthStencilBuffer = this._depthStencilBuffer;
  29724. }
  29725. if (this._lodTextureHigh) {
  29726. if (target._lodTextureHigh) {
  29727. target._lodTextureHigh.dispose();
  29728. }
  29729. target._lodTextureHigh = this._lodTextureHigh;
  29730. }
  29731. if (this._lodTextureMid) {
  29732. if (target._lodTextureMid) {
  29733. target._lodTextureMid.dispose();
  29734. }
  29735. target._lodTextureMid = this._lodTextureMid;
  29736. }
  29737. if (this._lodTextureLow) {
  29738. if (target._lodTextureLow) {
  29739. target._lodTextureLow.dispose();
  29740. }
  29741. target._lodTextureLow = this._lodTextureLow;
  29742. }
  29743. var cache = this._engine.getLoadedTexturesCache();
  29744. var index = cache.indexOf(this);
  29745. if (index !== -1) {
  29746. cache.splice(index, 1);
  29747. }
  29748. };
  29749. /**
  29750. * Dispose the current allocated resources
  29751. */
  29752. InternalTexture.prototype.dispose = function () {
  29753. if (!this._webGLTexture) {
  29754. return;
  29755. }
  29756. this._references--;
  29757. if (this._references === 0) {
  29758. this._engine._releaseTexture(this);
  29759. this._webGLTexture = null;
  29760. this.previous = null;
  29761. this.next = null;
  29762. }
  29763. };
  29764. /**
  29765. * The source of the texture data is unknown
  29766. */
  29767. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29768. /**
  29769. * Texture data comes from an URL
  29770. */
  29771. InternalTexture.DATASOURCE_URL = 1;
  29772. /**
  29773. * Texture data is only used for temporary storage
  29774. */
  29775. InternalTexture.DATASOURCE_TEMP = 2;
  29776. /**
  29777. * Texture data comes from raw data (ArrayBuffer)
  29778. */
  29779. InternalTexture.DATASOURCE_RAW = 3;
  29780. /**
  29781. * Texture content is dynamic (video or dynamic texture)
  29782. */
  29783. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29784. /**
  29785. * Texture content is generated by rendering to it
  29786. */
  29787. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29788. /**
  29789. * Texture content is part of a multi render target process
  29790. */
  29791. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29792. /**
  29793. * Texture data comes from a cube data file
  29794. */
  29795. InternalTexture.DATASOURCE_CUBE = 7;
  29796. /**
  29797. * Texture data comes from a raw cube data
  29798. */
  29799. InternalTexture.DATASOURCE_CUBERAW = 8;
  29800. /**
  29801. * Texture data come from a prefiltered cube data file
  29802. */
  29803. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29804. /**
  29805. * Texture content is raw 3D data
  29806. */
  29807. InternalTexture.DATASOURCE_RAW3D = 10;
  29808. /**
  29809. * Texture content is a depth texture
  29810. */
  29811. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29812. /**
  29813. * Texture data comes from a raw cube data encoded with RGBD
  29814. */
  29815. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29816. return InternalTexture;
  29817. }());
  29818. BABYLON.InternalTexture = InternalTexture;
  29819. })(BABYLON || (BABYLON = {}));
  29820. //# sourceMappingURL=babylon.internalTexture.js.map
  29821. var BABYLON;
  29822. (function (BABYLON) {
  29823. var BaseTexture = /** @class */ (function () {
  29824. function BaseTexture(scene) {
  29825. this._hasAlpha = false;
  29826. this.getAlphaFromRGB = false;
  29827. this.level = 1;
  29828. this.coordinatesIndex = 0;
  29829. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29830. /**
  29831. * | Value | Type | Description |
  29832. * | ----- | ------------------ | ----------- |
  29833. * | 0 | CLAMP_ADDRESSMODE | |
  29834. * | 1 | WRAP_ADDRESSMODE | |
  29835. * | 2 | MIRROR_ADDRESSMODE | |
  29836. */
  29837. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29838. /**
  29839. * | Value | Type | Description |
  29840. * | ----- | ------------------ | ----------- |
  29841. * | 0 | CLAMP_ADDRESSMODE | |
  29842. * | 1 | WRAP_ADDRESSMODE | |
  29843. * | 2 | MIRROR_ADDRESSMODE | |
  29844. */
  29845. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29846. /**
  29847. * | Value | Type | Description |
  29848. * | ----- | ------------------ | ----------- |
  29849. * | 0 | CLAMP_ADDRESSMODE | |
  29850. * | 1 | WRAP_ADDRESSMODE | |
  29851. * | 2 | MIRROR_ADDRESSMODE | |
  29852. */
  29853. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29854. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29855. this.isCube = false;
  29856. this.is3D = false;
  29857. this.gammaSpace = true;
  29858. this.invertZ = false;
  29859. this.lodLevelInAlpha = false;
  29860. this.isRenderTarget = false;
  29861. this.animations = new Array();
  29862. /**
  29863. * An event triggered when the texture is disposed.
  29864. */
  29865. this.onDisposeObservable = new BABYLON.Observable();
  29866. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29867. this._cachedSize = BABYLON.Size.Zero();
  29868. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29869. if (this._scene) {
  29870. this._scene.textures.push(this);
  29871. }
  29872. this._uid = null;
  29873. }
  29874. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29875. get: function () {
  29876. return this._hasAlpha;
  29877. },
  29878. set: function (value) {
  29879. if (this._hasAlpha === value) {
  29880. return;
  29881. }
  29882. this._hasAlpha = value;
  29883. if (this._scene) {
  29884. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29885. }
  29886. },
  29887. enumerable: true,
  29888. configurable: true
  29889. });
  29890. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29891. get: function () {
  29892. return this._coordinatesMode;
  29893. },
  29894. /**
  29895. * How a texture is mapped.
  29896. *
  29897. * | Value | Type | Description |
  29898. * | ----- | ----------------------------------- | ----------- |
  29899. * | 0 | EXPLICIT_MODE | |
  29900. * | 1 | SPHERICAL_MODE | |
  29901. * | 2 | PLANAR_MODE | |
  29902. * | 3 | CUBIC_MODE | |
  29903. * | 4 | PROJECTION_MODE | |
  29904. * | 5 | SKYBOX_MODE | |
  29905. * | 6 | INVCUBIC_MODE | |
  29906. * | 7 | EQUIRECTANGULAR_MODE | |
  29907. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29908. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29909. */
  29910. set: function (value) {
  29911. if (this._coordinatesMode === value) {
  29912. return;
  29913. }
  29914. this._coordinatesMode = value;
  29915. if (this._scene) {
  29916. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29917. }
  29918. },
  29919. enumerable: true,
  29920. configurable: true
  29921. });
  29922. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29923. /**
  29924. * Gets whether or not the texture contains RGBD data.
  29925. */
  29926. get: function () {
  29927. return this._texture != null && this._texture._isRGBD;
  29928. },
  29929. enumerable: true,
  29930. configurable: true
  29931. });
  29932. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29933. get: function () {
  29934. if (this._texture)
  29935. return this._texture._lodGenerationOffset;
  29936. return 0.0;
  29937. },
  29938. set: function (value) {
  29939. if (this._texture)
  29940. this._texture._lodGenerationOffset = value;
  29941. },
  29942. enumerable: true,
  29943. configurable: true
  29944. });
  29945. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29946. get: function () {
  29947. if (this._texture)
  29948. return this._texture._lodGenerationScale;
  29949. return 0.0;
  29950. },
  29951. set: function (value) {
  29952. if (this._texture)
  29953. this._texture._lodGenerationScale = value;
  29954. },
  29955. enumerable: true,
  29956. configurable: true
  29957. });
  29958. Object.defineProperty(BaseTexture.prototype, "uid", {
  29959. get: function () {
  29960. if (!this._uid) {
  29961. this._uid = BABYLON.Tools.RandomId();
  29962. }
  29963. return this._uid;
  29964. },
  29965. enumerable: true,
  29966. configurable: true
  29967. });
  29968. BaseTexture.prototype.toString = function () {
  29969. return this.name;
  29970. };
  29971. BaseTexture.prototype.getClassName = function () {
  29972. return "BaseTexture";
  29973. };
  29974. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29975. set: function (callback) {
  29976. if (this._onDisposeObserver) {
  29977. this.onDisposeObservable.remove(this._onDisposeObserver);
  29978. }
  29979. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29980. },
  29981. enumerable: true,
  29982. configurable: true
  29983. });
  29984. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29985. get: function () {
  29986. return true;
  29987. },
  29988. enumerable: true,
  29989. configurable: true
  29990. });
  29991. BaseTexture.prototype.getScene = function () {
  29992. return this._scene;
  29993. };
  29994. BaseTexture.prototype.getTextureMatrix = function () {
  29995. return BABYLON.Matrix.IdentityReadOnly;
  29996. };
  29997. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29998. return BABYLON.Matrix.IdentityReadOnly;
  29999. };
  30000. BaseTexture.prototype.getInternalTexture = function () {
  30001. return this._texture;
  30002. };
  30003. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30004. return !this.isBlocking || this.isReady();
  30005. };
  30006. BaseTexture.prototype.isReady = function () {
  30007. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30008. this.delayLoad();
  30009. return false;
  30010. }
  30011. if (this._texture) {
  30012. return this._texture.isReady;
  30013. }
  30014. return false;
  30015. };
  30016. BaseTexture.prototype.getSize = function () {
  30017. if (this._texture) {
  30018. if (this._texture.width) {
  30019. this._cachedSize.width = this._texture.width;
  30020. this._cachedSize.height = this._texture.height;
  30021. return this._cachedSize;
  30022. }
  30023. if (this._texture._size) {
  30024. this._cachedSize.width = this._texture._size;
  30025. this._cachedSize.height = this._texture._size;
  30026. return this._cachedSize;
  30027. }
  30028. }
  30029. return this._cachedSize;
  30030. };
  30031. BaseTexture.prototype.getBaseSize = function () {
  30032. if (!this.isReady() || !this._texture)
  30033. return BABYLON.Size.Zero();
  30034. if (this._texture._size) {
  30035. return new BABYLON.Size(this._texture._size, this._texture._size);
  30036. }
  30037. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30038. };
  30039. BaseTexture.prototype.scale = function (ratio) {
  30040. };
  30041. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30042. get: function () {
  30043. return false;
  30044. },
  30045. enumerable: true,
  30046. configurable: true
  30047. });
  30048. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30049. if (!this._scene) {
  30050. return null;
  30051. }
  30052. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30053. for (var index = 0; index < texturesCache.length; index++) {
  30054. var texturesCacheEntry = texturesCache[index];
  30055. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30056. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30057. texturesCacheEntry.incrementReferences();
  30058. return texturesCacheEntry;
  30059. }
  30060. }
  30061. }
  30062. return null;
  30063. };
  30064. BaseTexture.prototype._rebuild = function () {
  30065. };
  30066. BaseTexture.prototype.delayLoad = function () {
  30067. };
  30068. BaseTexture.prototype.clone = function () {
  30069. return null;
  30070. };
  30071. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30072. get: function () {
  30073. if (!this._texture) {
  30074. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30075. }
  30076. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30077. },
  30078. enumerable: true,
  30079. configurable: true
  30080. });
  30081. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30082. get: function () {
  30083. if (!this._texture) {
  30084. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30085. }
  30086. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30087. },
  30088. enumerable: true,
  30089. configurable: true
  30090. });
  30091. /**
  30092. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30093. * This will returns an RGBA array buffer containing either in values (0-255) or
  30094. * float values (0-1) depending of the underlying buffer type.
  30095. * @param faceIndex The face of the texture to read (in case of cube texture)
  30096. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30097. * @returns The Array buffer containing the pixels data.
  30098. */
  30099. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30100. if (faceIndex === void 0) { faceIndex = 0; }
  30101. if (level === void 0) { level = 0; }
  30102. if (!this._texture) {
  30103. return null;
  30104. }
  30105. var size = this.getSize();
  30106. var width = size.width;
  30107. var height = size.height;
  30108. var scene = this.getScene();
  30109. if (!scene) {
  30110. return null;
  30111. }
  30112. var engine = scene.getEngine();
  30113. if (level != 0) {
  30114. width = width / Math.pow(2, level);
  30115. height = height / Math.pow(2, level);
  30116. width = Math.round(width);
  30117. height = Math.round(height);
  30118. }
  30119. if (this._texture.isCube) {
  30120. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30121. }
  30122. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30123. };
  30124. BaseTexture.prototype.releaseInternalTexture = function () {
  30125. if (this._texture) {
  30126. this._texture.dispose();
  30127. this._texture = null;
  30128. }
  30129. };
  30130. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30131. get: function () {
  30132. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30133. return null;
  30134. }
  30135. if (!this._texture._sphericalPolynomial) {
  30136. this._texture._sphericalPolynomial =
  30137. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30138. }
  30139. return this._texture._sphericalPolynomial;
  30140. },
  30141. set: function (value) {
  30142. if (this._texture) {
  30143. this._texture._sphericalPolynomial = value;
  30144. }
  30145. },
  30146. enumerable: true,
  30147. configurable: true
  30148. });
  30149. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30150. get: function () {
  30151. if (this._texture) {
  30152. return this._texture._lodTextureHigh;
  30153. }
  30154. return null;
  30155. },
  30156. enumerable: true,
  30157. configurable: true
  30158. });
  30159. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30160. get: function () {
  30161. if (this._texture) {
  30162. return this._texture._lodTextureMid;
  30163. }
  30164. return null;
  30165. },
  30166. enumerable: true,
  30167. configurable: true
  30168. });
  30169. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30170. get: function () {
  30171. if (this._texture) {
  30172. return this._texture._lodTextureLow;
  30173. }
  30174. return null;
  30175. },
  30176. enumerable: true,
  30177. configurable: true
  30178. });
  30179. BaseTexture.prototype.dispose = function () {
  30180. if (!this._scene) {
  30181. return;
  30182. }
  30183. // Animations
  30184. this._scene.stopAnimation(this);
  30185. // Remove from scene
  30186. this._scene._removePendingData(this);
  30187. var index = this._scene.textures.indexOf(this);
  30188. if (index >= 0) {
  30189. this._scene.textures.splice(index, 1);
  30190. }
  30191. if (this._texture === undefined) {
  30192. return;
  30193. }
  30194. // Release
  30195. this.releaseInternalTexture();
  30196. // Callback
  30197. this.onDisposeObservable.notifyObservers(this);
  30198. this.onDisposeObservable.clear();
  30199. };
  30200. BaseTexture.prototype.serialize = function () {
  30201. if (!this.name) {
  30202. return null;
  30203. }
  30204. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30205. // Animations
  30206. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30207. return serializationObject;
  30208. };
  30209. BaseTexture.WhenAllReady = function (textures, callback) {
  30210. var numRemaining = textures.length;
  30211. if (numRemaining === 0) {
  30212. callback();
  30213. return;
  30214. }
  30215. var _loop_1 = function () {
  30216. texture = textures[i];
  30217. if (texture.isReady()) {
  30218. if (--numRemaining === 0) {
  30219. callback();
  30220. }
  30221. }
  30222. else {
  30223. onLoadObservable = texture.onLoadObservable;
  30224. var onLoadCallback_1 = function () {
  30225. onLoadObservable.removeCallback(onLoadCallback_1);
  30226. if (--numRemaining === 0) {
  30227. callback();
  30228. }
  30229. };
  30230. onLoadObservable.add(onLoadCallback_1);
  30231. }
  30232. };
  30233. var texture, onLoadObservable;
  30234. for (var i = 0; i < textures.length; i++) {
  30235. _loop_1();
  30236. }
  30237. };
  30238. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30239. __decorate([
  30240. BABYLON.serialize()
  30241. ], BaseTexture.prototype, "name", void 0);
  30242. __decorate([
  30243. BABYLON.serialize("hasAlpha")
  30244. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30245. __decorate([
  30246. BABYLON.serialize()
  30247. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30248. __decorate([
  30249. BABYLON.serialize()
  30250. ], BaseTexture.prototype, "level", void 0);
  30251. __decorate([
  30252. BABYLON.serialize()
  30253. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30254. __decorate([
  30255. BABYLON.serialize("coordinatesMode")
  30256. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30257. __decorate([
  30258. BABYLON.serialize()
  30259. ], BaseTexture.prototype, "wrapU", void 0);
  30260. __decorate([
  30261. BABYLON.serialize()
  30262. ], BaseTexture.prototype, "wrapV", void 0);
  30263. __decorate([
  30264. BABYLON.serialize()
  30265. ], BaseTexture.prototype, "wrapR", void 0);
  30266. __decorate([
  30267. BABYLON.serialize()
  30268. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30269. __decorate([
  30270. BABYLON.serialize()
  30271. ], BaseTexture.prototype, "isCube", void 0);
  30272. __decorate([
  30273. BABYLON.serialize()
  30274. ], BaseTexture.prototype, "is3D", void 0);
  30275. __decorate([
  30276. BABYLON.serialize()
  30277. ], BaseTexture.prototype, "gammaSpace", void 0);
  30278. __decorate([
  30279. BABYLON.serialize()
  30280. ], BaseTexture.prototype, "invertZ", void 0);
  30281. __decorate([
  30282. BABYLON.serialize()
  30283. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30284. __decorate([
  30285. BABYLON.serialize()
  30286. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30287. __decorate([
  30288. BABYLON.serialize()
  30289. ], BaseTexture.prototype, "lodGenerationScale", null);
  30290. __decorate([
  30291. BABYLON.serialize()
  30292. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30293. return BaseTexture;
  30294. }());
  30295. BABYLON.BaseTexture = BaseTexture;
  30296. })(BABYLON || (BABYLON = {}));
  30297. //# sourceMappingURL=babylon.baseTexture.js.map
  30298. var BABYLON;
  30299. (function (BABYLON) {
  30300. var Texture = /** @class */ (function (_super) {
  30301. __extends(Texture, _super);
  30302. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30303. if (noMipmap === void 0) { noMipmap = false; }
  30304. if (invertY === void 0) { invertY = true; }
  30305. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30306. if (onLoad === void 0) { onLoad = null; }
  30307. if (onError === void 0) { onError = null; }
  30308. if (buffer === void 0) { buffer = null; }
  30309. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30310. var _this = _super.call(this, scene) || this;
  30311. _this.uOffset = 0;
  30312. _this.vOffset = 0;
  30313. _this.uScale = 1.0;
  30314. _this.vScale = 1.0;
  30315. _this.uAng = 0;
  30316. _this.vAng = 0;
  30317. _this.wAng = 0;
  30318. /**
  30319. * Defines the center of rotation (U)
  30320. */
  30321. _this.uRotationCenter = 0.5;
  30322. /**
  30323. * Defines the center of rotation (V)
  30324. */
  30325. _this.vRotationCenter = 0.5;
  30326. /**
  30327. * Defines the center of rotation (W)
  30328. */
  30329. _this.wRotationCenter = 0.5;
  30330. _this._isBlocking = true;
  30331. _this.name = url || "";
  30332. _this.url = url;
  30333. _this._noMipmap = noMipmap;
  30334. _this._invertY = invertY;
  30335. _this._samplingMode = samplingMode;
  30336. _this._buffer = buffer;
  30337. _this._deleteBuffer = deleteBuffer;
  30338. if (format) {
  30339. _this._format = format;
  30340. }
  30341. scene = _this.getScene();
  30342. if (!scene) {
  30343. return _this;
  30344. }
  30345. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30346. var load = function () {
  30347. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30348. _this.onLoadObservable.notifyObservers(_this);
  30349. }
  30350. if (onLoad) {
  30351. onLoad();
  30352. }
  30353. if (!_this.isBlocking && scene) {
  30354. scene.resetCachedMaterial();
  30355. }
  30356. };
  30357. if (!_this.url) {
  30358. _this._delayedOnLoad = load;
  30359. _this._delayedOnError = onError;
  30360. return _this;
  30361. }
  30362. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30363. if (!_this._texture) {
  30364. if (!scene.useDelayedTextureLoading) {
  30365. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30366. if (deleteBuffer) {
  30367. delete _this._buffer;
  30368. }
  30369. }
  30370. else {
  30371. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30372. _this._delayedOnLoad = load;
  30373. _this._delayedOnError = onError;
  30374. }
  30375. }
  30376. else {
  30377. if (_this._texture.isReady) {
  30378. BABYLON.Tools.SetImmediate(function () { return load(); });
  30379. }
  30380. else {
  30381. _this._texture.onLoadedObservable.add(load);
  30382. }
  30383. }
  30384. return _this;
  30385. }
  30386. Object.defineProperty(Texture.prototype, "noMipmap", {
  30387. get: function () {
  30388. return this._noMipmap;
  30389. },
  30390. enumerable: true,
  30391. configurable: true
  30392. });
  30393. Object.defineProperty(Texture.prototype, "isBlocking", {
  30394. get: function () {
  30395. return this._isBlocking;
  30396. },
  30397. set: function (value) {
  30398. this._isBlocking = value;
  30399. },
  30400. enumerable: true,
  30401. configurable: true
  30402. });
  30403. Object.defineProperty(Texture.prototype, "samplingMode", {
  30404. get: function () {
  30405. return this._samplingMode;
  30406. },
  30407. enumerable: true,
  30408. configurable: true
  30409. });
  30410. /**
  30411. * Update the url (and optional buffer) of this texture if url was null during construction.
  30412. * @param url the url of the texture
  30413. * @param buffer the buffer of the texture (defaults to null)
  30414. */
  30415. Texture.prototype.updateURL = function (url, buffer) {
  30416. if (buffer === void 0) { buffer = null; }
  30417. if (this.url) {
  30418. throw new Error("URL is already set");
  30419. }
  30420. this.url = url;
  30421. this._buffer = buffer;
  30422. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30423. this.delayLoad();
  30424. };
  30425. Texture.prototype.delayLoad = function () {
  30426. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30427. return;
  30428. }
  30429. var scene = this.getScene();
  30430. if (!scene) {
  30431. return;
  30432. }
  30433. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30434. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30435. if (!this._texture) {
  30436. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30437. if (this._deleteBuffer) {
  30438. delete this._buffer;
  30439. }
  30440. }
  30441. else {
  30442. if (this._delayedOnLoad) {
  30443. if (this._texture.isReady) {
  30444. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30445. }
  30446. else {
  30447. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30448. }
  30449. }
  30450. }
  30451. this._delayedOnLoad = null;
  30452. this._delayedOnError = null;
  30453. };
  30454. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30455. if (!this._texture) {
  30456. return;
  30457. }
  30458. var scene = this.getScene();
  30459. if (!scene) {
  30460. return;
  30461. }
  30462. this._samplingMode = samplingMode;
  30463. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30464. };
  30465. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30466. x *= this.uScale;
  30467. y *= this.vScale;
  30468. x -= this.uRotationCenter * this.uScale;
  30469. y -= this.vRotationCenter * this.vScale;
  30470. z -= this.wRotationCenter;
  30471. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30472. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30473. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30474. t.z += this.wRotationCenter;
  30475. };
  30476. Texture.prototype.getTextureMatrix = function () {
  30477. var _this = this;
  30478. if (this.uOffset === this._cachedUOffset &&
  30479. this.vOffset === this._cachedVOffset &&
  30480. this.uScale === this._cachedUScale &&
  30481. this.vScale === this._cachedVScale &&
  30482. this.uAng === this._cachedUAng &&
  30483. this.vAng === this._cachedVAng &&
  30484. this.wAng === this._cachedWAng) {
  30485. return this._cachedTextureMatrix;
  30486. }
  30487. this._cachedUOffset = this.uOffset;
  30488. this._cachedVOffset = this.vOffset;
  30489. this._cachedUScale = this.uScale;
  30490. this._cachedVScale = this.vScale;
  30491. this._cachedUAng = this.uAng;
  30492. this._cachedVAng = this.vAng;
  30493. this._cachedWAng = this.wAng;
  30494. if (!this._cachedTextureMatrix) {
  30495. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30496. this._rowGenerationMatrix = new BABYLON.Matrix();
  30497. this._t0 = BABYLON.Vector3.Zero();
  30498. this._t1 = BABYLON.Vector3.Zero();
  30499. this._t2 = BABYLON.Vector3.Zero();
  30500. }
  30501. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30502. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30503. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30504. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30505. this._t1.subtractInPlace(this._t0);
  30506. this._t2.subtractInPlace(this._t0);
  30507. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30508. this._cachedTextureMatrix.m[0] = this._t1.x;
  30509. this._cachedTextureMatrix.m[1] = this._t1.y;
  30510. this._cachedTextureMatrix.m[2] = this._t1.z;
  30511. this._cachedTextureMatrix.m[4] = this._t2.x;
  30512. this._cachedTextureMatrix.m[5] = this._t2.y;
  30513. this._cachedTextureMatrix.m[6] = this._t2.z;
  30514. this._cachedTextureMatrix.m[8] = this._t0.x;
  30515. this._cachedTextureMatrix.m[9] = this._t0.y;
  30516. this._cachedTextureMatrix.m[10] = this._t0.z;
  30517. var scene = this.getScene();
  30518. if (!scene) {
  30519. return this._cachedTextureMatrix;
  30520. }
  30521. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30522. return mat.hasTexture(_this);
  30523. });
  30524. return this._cachedTextureMatrix;
  30525. };
  30526. Texture.prototype.getReflectionTextureMatrix = function () {
  30527. var _this = this;
  30528. var scene = this.getScene();
  30529. if (!scene) {
  30530. return this._cachedTextureMatrix;
  30531. }
  30532. if (this.uOffset === this._cachedUOffset &&
  30533. this.vOffset === this._cachedVOffset &&
  30534. this.uScale === this._cachedUScale &&
  30535. this.vScale === this._cachedVScale &&
  30536. this.coordinatesMode === this._cachedCoordinatesMode) {
  30537. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30538. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30539. return this._cachedTextureMatrix;
  30540. }
  30541. }
  30542. else {
  30543. return this._cachedTextureMatrix;
  30544. }
  30545. }
  30546. if (!this._cachedTextureMatrix) {
  30547. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30548. }
  30549. if (!this._projectionModeMatrix) {
  30550. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30551. }
  30552. this._cachedUOffset = this.uOffset;
  30553. this._cachedVOffset = this.vOffset;
  30554. this._cachedUScale = this.uScale;
  30555. this._cachedVScale = this.vScale;
  30556. this._cachedCoordinatesMode = this.coordinatesMode;
  30557. switch (this.coordinatesMode) {
  30558. case Texture.PLANAR_MODE:
  30559. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30560. this._cachedTextureMatrix[0] = this.uScale;
  30561. this._cachedTextureMatrix[5] = this.vScale;
  30562. this._cachedTextureMatrix[12] = this.uOffset;
  30563. this._cachedTextureMatrix[13] = this.vOffset;
  30564. break;
  30565. case Texture.PROJECTION_MODE:
  30566. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30567. this._projectionModeMatrix.m[0] = 0.5;
  30568. this._projectionModeMatrix.m[5] = -0.5;
  30569. this._projectionModeMatrix.m[10] = 0.0;
  30570. this._projectionModeMatrix.m[12] = 0.5;
  30571. this._projectionModeMatrix.m[13] = 0.5;
  30572. this._projectionModeMatrix.m[14] = 1.0;
  30573. this._projectionModeMatrix.m[15] = 1.0;
  30574. var projectionMatrix = scene.getProjectionMatrix();
  30575. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30576. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30577. break;
  30578. default:
  30579. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30580. break;
  30581. }
  30582. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30583. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30584. });
  30585. return this._cachedTextureMatrix;
  30586. };
  30587. Texture.prototype.clone = function () {
  30588. var _this = this;
  30589. return BABYLON.SerializationHelper.Clone(function () {
  30590. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30591. }, this);
  30592. };
  30593. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30594. get: function () {
  30595. if (!this._onLoadObservable) {
  30596. this._onLoadObservable = new BABYLON.Observable();
  30597. }
  30598. return this._onLoadObservable;
  30599. },
  30600. enumerable: true,
  30601. configurable: true
  30602. });
  30603. Texture.prototype.serialize = function () {
  30604. var serializationObject = _super.prototype.serialize.call(this);
  30605. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30606. serializationObject.base64String = this._buffer;
  30607. serializationObject.name = serializationObject.name.replace("data:", "");
  30608. }
  30609. serializationObject.invertY = this._invertY;
  30610. serializationObject.samplingMode = this.samplingMode;
  30611. return serializationObject;
  30612. };
  30613. Texture.prototype.getClassName = function () {
  30614. return "Texture";
  30615. };
  30616. Texture.prototype.dispose = function () {
  30617. _super.prototype.dispose.call(this);
  30618. if (this._onLoadObservable) {
  30619. this._onLoadObservable.clear();
  30620. this._onLoadObservable = null;
  30621. }
  30622. this._delayedOnLoad = null;
  30623. this._delayedOnError = null;
  30624. };
  30625. // Statics
  30626. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30627. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30628. if (onLoad === void 0) { onLoad = null; }
  30629. if (onError === void 0) { onError = null; }
  30630. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30631. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30632. };
  30633. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30634. if (parsedTexture.customType) {
  30635. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30636. // Update Sampling Mode
  30637. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30638. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30639. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30640. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30641. }
  30642. }
  30643. return parsedCustomTexture;
  30644. }
  30645. if (parsedTexture.isCube) {
  30646. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30647. }
  30648. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30649. return null;
  30650. }
  30651. var texture = BABYLON.SerializationHelper.Parse(function () {
  30652. var generateMipMaps = true;
  30653. if (parsedTexture.noMipmap) {
  30654. generateMipMaps = false;
  30655. }
  30656. if (parsedTexture.mirrorPlane) {
  30657. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30658. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30659. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30660. return mirrorTexture;
  30661. }
  30662. else if (parsedTexture.isRenderTarget) {
  30663. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30664. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30665. return renderTargetTexture;
  30666. }
  30667. else {
  30668. var texture;
  30669. if (parsedTexture.base64String) {
  30670. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30671. }
  30672. else {
  30673. var url = rootUrl + parsedTexture.name;
  30674. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30675. url = parsedTexture.url;
  30676. }
  30677. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30678. }
  30679. return texture;
  30680. }
  30681. }, parsedTexture, scene);
  30682. // Update Sampling Mode
  30683. if (parsedTexture.samplingMode) {
  30684. var sampling = parsedTexture.samplingMode;
  30685. if (texture._samplingMode !== sampling) {
  30686. texture.updateSamplingMode(sampling);
  30687. }
  30688. }
  30689. // Animations
  30690. if (parsedTexture.animations) {
  30691. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30692. var parsedAnimation = parsedTexture.animations[animationIndex];
  30693. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30694. }
  30695. }
  30696. return texture;
  30697. };
  30698. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30699. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30700. if (noMipmap === void 0) { noMipmap = false; }
  30701. if (invertY === void 0) { invertY = true; }
  30702. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30703. if (onLoad === void 0) { onLoad = null; }
  30704. if (onError === void 0) { onError = null; }
  30705. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30706. if (name.substr(0, 5) !== "data:") {
  30707. name = "data:" + name;
  30708. }
  30709. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30710. };
  30711. // Constants
  30712. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30713. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30714. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30715. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30716. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30717. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30718. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30719. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30720. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30721. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30722. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30723. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30724. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30725. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30726. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30727. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30728. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30729. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30730. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30731. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30732. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30733. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30734. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30735. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30736. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30737. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30738. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30739. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30740. /**
  30741. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  30742. */
  30743. Texture.UseSerializedUrlIfAny = false;
  30744. __decorate([
  30745. BABYLON.serialize()
  30746. ], Texture.prototype, "url", void 0);
  30747. __decorate([
  30748. BABYLON.serialize()
  30749. ], Texture.prototype, "uOffset", void 0);
  30750. __decorate([
  30751. BABYLON.serialize()
  30752. ], Texture.prototype, "vOffset", void 0);
  30753. __decorate([
  30754. BABYLON.serialize()
  30755. ], Texture.prototype, "uScale", void 0);
  30756. __decorate([
  30757. BABYLON.serialize()
  30758. ], Texture.prototype, "vScale", void 0);
  30759. __decorate([
  30760. BABYLON.serialize()
  30761. ], Texture.prototype, "uAng", void 0);
  30762. __decorate([
  30763. BABYLON.serialize()
  30764. ], Texture.prototype, "vAng", void 0);
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], Texture.prototype, "wAng", void 0);
  30768. __decorate([
  30769. BABYLON.serialize()
  30770. ], Texture.prototype, "uRotationCenter", void 0);
  30771. __decorate([
  30772. BABYLON.serialize()
  30773. ], Texture.prototype, "vRotationCenter", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], Texture.prototype, "wRotationCenter", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], Texture.prototype, "isBlocking", null);
  30780. return Texture;
  30781. }(BABYLON.BaseTexture));
  30782. BABYLON.Texture = Texture;
  30783. })(BABYLON || (BABYLON = {}));
  30784. //# sourceMappingURL=babylon.texture.js.map
  30785. var BABYLON;
  30786. (function (BABYLON) {
  30787. /**
  30788. * @hidden
  30789. **/
  30790. var _InstancesBatch = /** @class */ (function () {
  30791. function _InstancesBatch() {
  30792. this.mustReturn = false;
  30793. this.visibleInstances = new Array();
  30794. this.renderSelf = new Array();
  30795. }
  30796. return _InstancesBatch;
  30797. }());
  30798. BABYLON._InstancesBatch = _InstancesBatch;
  30799. var Mesh = /** @class */ (function (_super) {
  30800. __extends(Mesh, _super);
  30801. /**
  30802. * @constructor
  30803. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30804. * @param {Scene} scene The scene to add this mesh to.
  30805. * @param {Node} parent The parent of this mesh, if it has one
  30806. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30807. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30808. * When false, achieved by calling a clone(), also passing False.
  30809. * This will make creation of children, recursive.
  30810. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30811. */
  30812. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30813. if (scene === void 0) { scene = null; }
  30814. if (parent === void 0) { parent = null; }
  30815. if (source === void 0) { source = null; }
  30816. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30817. var _this = _super.call(this, name, scene) || this;
  30818. // Events
  30819. /**
  30820. * An event triggered before rendering the mesh
  30821. */
  30822. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30823. /**
  30824. * An event triggered after rendering the mesh
  30825. */
  30826. _this.onAfterRenderObservable = new BABYLON.Observable();
  30827. /**
  30828. * An event triggered before drawing the mesh
  30829. */
  30830. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30831. // Members
  30832. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30833. _this.instances = new Array();
  30834. _this._LODLevels = new Array();
  30835. _this._visibleInstances = {};
  30836. _this._renderIdForInstances = new Array();
  30837. _this._batchCache = new _InstancesBatch();
  30838. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30839. // Use by builder only to know what orientation were the mesh build in.
  30840. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30841. _this.overrideMaterialSideOrientation = null;
  30842. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30843. // Will be used to save a source mesh reference, If any
  30844. _this._source = null;
  30845. scene = _this.getScene();
  30846. if (source) {
  30847. // Geometry
  30848. if (source._geometry) {
  30849. source._geometry.applyToMesh(_this);
  30850. }
  30851. // Deep copy
  30852. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30853. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  30854. // Source mesh
  30855. _this._source = source;
  30856. // Metadata
  30857. if (source.metadata && source.metadata.clone) {
  30858. _this.metadata = source.metadata.clone();
  30859. }
  30860. else {
  30861. _this.metadata = source.metadata;
  30862. }
  30863. // Tags
  30864. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30865. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30866. }
  30867. // Parent
  30868. _this.parent = source.parent;
  30869. // Pivot
  30870. _this.setPivotMatrix(source.getPivotMatrix());
  30871. _this.id = name + "." + source.id;
  30872. // Material
  30873. _this.material = source.material;
  30874. var index;
  30875. if (!doNotCloneChildren) {
  30876. // Children
  30877. var directDescendants = source.getDescendants(true);
  30878. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30879. var child = directDescendants[index_1];
  30880. if (child.clone) {
  30881. child.clone(name + "." + child.name, _this);
  30882. }
  30883. }
  30884. }
  30885. // Physics clone
  30886. var physicsEngine = _this.getScene().getPhysicsEngine();
  30887. if (clonePhysicsImpostor && physicsEngine) {
  30888. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30889. if (impostor) {
  30890. _this.physicsImpostor = impostor.clone(_this);
  30891. }
  30892. }
  30893. // Particles
  30894. for (index = 0; index < scene.particleSystems.length; index++) {
  30895. var system = scene.particleSystems[index];
  30896. if (system.emitter === source) {
  30897. system.clone(system.name, _this);
  30898. }
  30899. }
  30900. _this.refreshBoundingInfo();
  30901. _this.computeWorldMatrix(true);
  30902. }
  30903. // Parent
  30904. if (parent !== null) {
  30905. _this.parent = parent;
  30906. }
  30907. return _this;
  30908. }
  30909. Object.defineProperty(Mesh, "FRONTSIDE", {
  30910. /**
  30911. * Mesh side orientation : usually the external or front surface
  30912. */
  30913. get: function () {
  30914. return Mesh._FRONTSIDE;
  30915. },
  30916. enumerable: true,
  30917. configurable: true
  30918. });
  30919. Object.defineProperty(Mesh, "BACKSIDE", {
  30920. /**
  30921. * Mesh side orientation : usually the internal or back surface
  30922. */
  30923. get: function () {
  30924. return Mesh._BACKSIDE;
  30925. },
  30926. enumerable: true,
  30927. configurable: true
  30928. });
  30929. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30930. /**
  30931. * Mesh side orientation : both internal and external or front and back surfaces
  30932. */
  30933. get: function () {
  30934. return Mesh._DOUBLESIDE;
  30935. },
  30936. enumerable: true,
  30937. configurable: true
  30938. });
  30939. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30940. /**
  30941. * Mesh side orientation : by default, `FRONTSIDE`
  30942. */
  30943. get: function () {
  30944. return Mesh._DEFAULTSIDE;
  30945. },
  30946. enumerable: true,
  30947. configurable: true
  30948. });
  30949. Object.defineProperty(Mesh, "NO_CAP", {
  30950. /**
  30951. * Mesh cap setting : no cap
  30952. */
  30953. get: function () {
  30954. return Mesh._NO_CAP;
  30955. },
  30956. enumerable: true,
  30957. configurable: true
  30958. });
  30959. Object.defineProperty(Mesh, "CAP_START", {
  30960. /**
  30961. * Mesh cap setting : one cap at the beginning of the mesh
  30962. */
  30963. get: function () {
  30964. return Mesh._CAP_START;
  30965. },
  30966. enumerable: true,
  30967. configurable: true
  30968. });
  30969. Object.defineProperty(Mesh, "CAP_END", {
  30970. /**
  30971. * Mesh cap setting : one cap at the end of the mesh
  30972. */
  30973. get: function () {
  30974. return Mesh._CAP_END;
  30975. },
  30976. enumerable: true,
  30977. configurable: true
  30978. });
  30979. Object.defineProperty(Mesh, "CAP_ALL", {
  30980. /**
  30981. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30982. */
  30983. get: function () {
  30984. return Mesh._CAP_ALL;
  30985. },
  30986. enumerable: true,
  30987. configurable: true
  30988. });
  30989. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30990. set: function (callback) {
  30991. if (this._onBeforeDrawObserver) {
  30992. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30993. }
  30994. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30995. },
  30996. enumerable: true,
  30997. configurable: true
  30998. });
  30999. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31000. get: function () {
  31001. return this._morphTargetManager;
  31002. },
  31003. set: function (value) {
  31004. if (this._morphTargetManager === value) {
  31005. return;
  31006. }
  31007. this._morphTargetManager = value;
  31008. this._syncGeometryWithMorphTargetManager();
  31009. },
  31010. enumerable: true,
  31011. configurable: true
  31012. });
  31013. Object.defineProperty(Mesh.prototype, "source", {
  31014. get: function () {
  31015. return this._source;
  31016. },
  31017. enumerable: true,
  31018. configurable: true
  31019. });
  31020. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31021. get: function () {
  31022. return this._unIndexed;
  31023. },
  31024. set: function (value) {
  31025. if (this._unIndexed !== value) {
  31026. this._unIndexed = value;
  31027. this._markSubMeshesAsAttributesDirty();
  31028. }
  31029. },
  31030. enumerable: true,
  31031. configurable: true
  31032. });
  31033. // Methods
  31034. /**
  31035. * Returns the string "Mesh".
  31036. */
  31037. Mesh.prototype.getClassName = function () {
  31038. return "Mesh";
  31039. };
  31040. /**
  31041. * Returns a string.
  31042. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31043. */
  31044. Mesh.prototype.toString = function (fullDetails) {
  31045. var ret = _super.prototype.toString.call(this, fullDetails);
  31046. ret += ", n vertices: " + this.getTotalVertices();
  31047. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31048. if (this.animations) {
  31049. for (var i = 0; i < this.animations.length; i++) {
  31050. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31051. }
  31052. }
  31053. if (fullDetails) {
  31054. if (this._geometry) {
  31055. var ib = this.getIndices();
  31056. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31057. if (vb && ib) {
  31058. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31059. }
  31060. }
  31061. else {
  31062. ret += ", flat shading: UNKNOWN";
  31063. }
  31064. }
  31065. return ret;
  31066. };
  31067. Mesh.prototype._unBindEffect = function () {
  31068. _super.prototype._unBindEffect.call(this);
  31069. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31070. var instance = _a[_i];
  31071. instance._unBindEffect();
  31072. }
  31073. };
  31074. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31075. /**
  31076. * True if the mesh has some Levels Of Details (LOD).
  31077. * Returns a boolean.
  31078. */
  31079. get: function () {
  31080. return this._LODLevels.length > 0;
  31081. },
  31082. enumerable: true,
  31083. configurable: true
  31084. });
  31085. /**
  31086. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31087. * @returns an array of {BABYLON.MeshLODLevel}
  31088. */
  31089. Mesh.prototype.getLODLevels = function () {
  31090. return this._LODLevels;
  31091. };
  31092. Mesh.prototype._sortLODLevels = function () {
  31093. this._LODLevels.sort(function (a, b) {
  31094. if (a.distance < b.distance) {
  31095. return 1;
  31096. }
  31097. if (a.distance > b.distance) {
  31098. return -1;
  31099. }
  31100. return 0;
  31101. });
  31102. };
  31103. /**
  31104. * Add a mesh as LOD level triggered at the given distance.
  31105. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31106. * @param distance The distance from the center of the object to show this level
  31107. * @param mesh The mesh to be added as LOD level (can be null)
  31108. * @return This mesh (for chaining)
  31109. */
  31110. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31111. if (mesh && mesh._masterMesh) {
  31112. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31113. return this;
  31114. }
  31115. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31116. this._LODLevels.push(level);
  31117. if (mesh) {
  31118. mesh._masterMesh = this;
  31119. }
  31120. this._sortLODLevels();
  31121. return this;
  31122. };
  31123. /**
  31124. * Returns the LOD level mesh at the passed distance or null if not found.
  31125. * It is related to the method `addLODLevel(distance, mesh)`.
  31126. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31127. * Returns an object Mesh or `null`.
  31128. */
  31129. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31130. for (var index = 0; index < this._LODLevels.length; index++) {
  31131. var level = this._LODLevels[index];
  31132. if (level.distance === distance) {
  31133. return level.mesh;
  31134. }
  31135. }
  31136. return null;
  31137. };
  31138. /**
  31139. * Remove a mesh from the LOD array
  31140. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31141. * @param {Mesh} mesh The mesh to be removed.
  31142. * @return {Mesh} This mesh (for chaining)
  31143. */
  31144. Mesh.prototype.removeLODLevel = function (mesh) {
  31145. for (var index = 0; index < this._LODLevels.length; index++) {
  31146. if (this._LODLevels[index].mesh === mesh) {
  31147. this._LODLevels.splice(index, 1);
  31148. if (mesh) {
  31149. mesh._masterMesh = null;
  31150. }
  31151. }
  31152. }
  31153. this._sortLODLevels();
  31154. return this;
  31155. };
  31156. /**
  31157. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31158. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31159. */
  31160. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31161. if (!this._LODLevels || this._LODLevels.length === 0) {
  31162. return this;
  31163. }
  31164. var bSphere;
  31165. if (boundingSphere) {
  31166. bSphere = boundingSphere;
  31167. }
  31168. else {
  31169. var boundingInfo = this.getBoundingInfo();
  31170. bSphere = boundingInfo.boundingSphere;
  31171. }
  31172. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31173. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31174. if (this.onLODLevelSelection) {
  31175. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31176. }
  31177. return this;
  31178. }
  31179. for (var index = 0; index < this._LODLevels.length; index++) {
  31180. var level = this._LODLevels[index];
  31181. if (level.distance < distanceToCamera) {
  31182. if (level.mesh) {
  31183. level.mesh._preActivate();
  31184. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31185. }
  31186. if (this.onLODLevelSelection) {
  31187. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31188. }
  31189. return level.mesh;
  31190. }
  31191. }
  31192. if (this.onLODLevelSelection) {
  31193. this.onLODLevelSelection(distanceToCamera, this, this);
  31194. }
  31195. return this;
  31196. };
  31197. Object.defineProperty(Mesh.prototype, "geometry", {
  31198. /**
  31199. * Returns the mesh internal Geometry object.
  31200. */
  31201. get: function () {
  31202. return this._geometry;
  31203. },
  31204. enumerable: true,
  31205. configurable: true
  31206. });
  31207. /**
  31208. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31209. */
  31210. Mesh.prototype.getTotalVertices = function () {
  31211. if (this._geometry === null || this._geometry === undefined) {
  31212. return 0;
  31213. }
  31214. return this._geometry.getTotalVertices();
  31215. };
  31216. /**
  31217. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31218. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31219. * You can force the copy with forceCopy === true
  31220. * Returns null if the mesh has no geometry or no vertex buffer.
  31221. * Possible `kind` values :
  31222. * - BABYLON.VertexBuffer.PositionKind
  31223. * - BABYLON.VertexBuffer.UVKind
  31224. * - BABYLON.VertexBuffer.UV2Kind
  31225. * - BABYLON.VertexBuffer.UV3Kind
  31226. * - BABYLON.VertexBuffer.UV4Kind
  31227. * - BABYLON.VertexBuffer.UV5Kind
  31228. * - BABYLON.VertexBuffer.UV6Kind
  31229. * - BABYLON.VertexBuffer.ColorKind
  31230. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31231. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31232. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31233. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31234. */
  31235. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31236. if (!this._geometry) {
  31237. return null;
  31238. }
  31239. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31240. };
  31241. /**
  31242. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31243. * Returns `null` if the mesh has no geometry.
  31244. * Possible `kind` values :
  31245. * - BABYLON.VertexBuffer.PositionKind
  31246. * - BABYLON.VertexBuffer.UVKind
  31247. * - BABYLON.VertexBuffer.UV2Kind
  31248. * - BABYLON.VertexBuffer.UV3Kind
  31249. * - BABYLON.VertexBuffer.UV4Kind
  31250. * - BABYLON.VertexBuffer.UV5Kind
  31251. * - BABYLON.VertexBuffer.UV6Kind
  31252. * - BABYLON.VertexBuffer.ColorKind
  31253. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31254. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31255. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31256. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31257. */
  31258. Mesh.prototype.getVertexBuffer = function (kind) {
  31259. if (!this._geometry) {
  31260. return null;
  31261. }
  31262. return this._geometry.getVertexBuffer(kind);
  31263. };
  31264. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31265. if (!this._geometry) {
  31266. if (this._delayInfo) {
  31267. return this._delayInfo.indexOf(kind) !== -1;
  31268. }
  31269. return false;
  31270. }
  31271. return this._geometry.isVerticesDataPresent(kind);
  31272. };
  31273. /**
  31274. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31275. * Possible `kind` values :
  31276. * - BABYLON.VertexBuffer.PositionKind
  31277. * - BABYLON.VertexBuffer.UVKind
  31278. * - BABYLON.VertexBuffer.UV2Kind
  31279. * - BABYLON.VertexBuffer.UV3Kind
  31280. * - BABYLON.VertexBuffer.UV4Kind
  31281. * - BABYLON.VertexBuffer.UV5Kind
  31282. * - BABYLON.VertexBuffer.UV6Kind
  31283. * - BABYLON.VertexBuffer.ColorKind
  31284. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31285. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31286. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31287. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31288. */
  31289. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31290. if (!this._geometry) {
  31291. if (this._delayInfo) {
  31292. return this._delayInfo.indexOf(kind) !== -1;
  31293. }
  31294. return false;
  31295. }
  31296. return this._geometry.isVertexBufferUpdatable(kind);
  31297. };
  31298. /**
  31299. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31300. * Possible `kind` values :
  31301. * - BABYLON.VertexBuffer.PositionKind
  31302. * - BABYLON.VertexBuffer.UVKind
  31303. * - BABYLON.VertexBuffer.UV2Kind
  31304. * - BABYLON.VertexBuffer.UV3Kind
  31305. * - BABYLON.VertexBuffer.UV4Kind
  31306. * - BABYLON.VertexBuffer.UV5Kind
  31307. * - BABYLON.VertexBuffer.UV6Kind
  31308. * - BABYLON.VertexBuffer.ColorKind
  31309. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31310. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31311. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31312. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31313. */
  31314. Mesh.prototype.getVerticesDataKinds = function () {
  31315. if (!this._geometry) {
  31316. var result = new Array();
  31317. if (this._delayInfo) {
  31318. this._delayInfo.forEach(function (kind, index, array) {
  31319. result.push(kind);
  31320. });
  31321. }
  31322. return result;
  31323. }
  31324. return this._geometry.getVerticesDataKinds();
  31325. };
  31326. /**
  31327. * Returns a positive integer : the total number of indices in this mesh geometry.
  31328. * Returns zero if the mesh has no geometry.
  31329. */
  31330. Mesh.prototype.getTotalIndices = function () {
  31331. if (!this._geometry) {
  31332. return 0;
  31333. }
  31334. return this._geometry.getTotalIndices();
  31335. };
  31336. /**
  31337. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31338. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31339. * Returns an empty array if the mesh has no geometry.
  31340. */
  31341. Mesh.prototype.getIndices = function (copyWhenShared) {
  31342. if (!this._geometry) {
  31343. return [];
  31344. }
  31345. return this._geometry.getIndices(copyWhenShared);
  31346. };
  31347. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31348. get: function () {
  31349. return this._masterMesh !== null && this._masterMesh !== undefined;
  31350. },
  31351. enumerable: true,
  31352. configurable: true
  31353. });
  31354. /**
  31355. * Determine if the current mesh is ready to be rendered
  31356. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31357. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31358. * @returns true if all associated assets are ready (material, textures, shaders)
  31359. */
  31360. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31361. if (completeCheck === void 0) { completeCheck = false; }
  31362. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31363. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31364. return false;
  31365. }
  31366. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31367. return false;
  31368. }
  31369. if (!this.subMeshes || this.subMeshes.length === 0) {
  31370. return true;
  31371. }
  31372. if (!completeCheck) {
  31373. return true;
  31374. }
  31375. var engine = this.getEngine();
  31376. var scene = this.getScene();
  31377. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31378. this.computeWorldMatrix();
  31379. var mat = this.material || scene.defaultMaterial;
  31380. if (mat) {
  31381. if (mat.storeEffectOnSubMeshes) {
  31382. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31383. var subMesh = _a[_i];
  31384. var effectiveMaterial = subMesh.getMaterial();
  31385. if (effectiveMaterial) {
  31386. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31387. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31388. return false;
  31389. }
  31390. }
  31391. else {
  31392. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31393. return false;
  31394. }
  31395. }
  31396. }
  31397. }
  31398. }
  31399. else {
  31400. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31401. return false;
  31402. }
  31403. }
  31404. }
  31405. // Shadows
  31406. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31407. var light = _c[_b];
  31408. var generator = light.getShadowGenerator();
  31409. if (generator) {
  31410. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31411. var subMesh = _e[_d];
  31412. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31413. return false;
  31414. }
  31415. }
  31416. }
  31417. }
  31418. // LOD
  31419. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31420. var lod = _g[_f];
  31421. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31422. return false;
  31423. }
  31424. }
  31425. return true;
  31426. };
  31427. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31428. /**
  31429. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31430. * This property is pertinent only for updatable parametric shapes.
  31431. */
  31432. get: function () {
  31433. return this._areNormalsFrozen;
  31434. },
  31435. enumerable: true,
  31436. configurable: true
  31437. });
  31438. /**
  31439. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31440. * It has no effect at all on other shapes.
  31441. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31442. * Returns the Mesh.
  31443. */
  31444. Mesh.prototype.freezeNormals = function () {
  31445. this._areNormalsFrozen = true;
  31446. return this;
  31447. };
  31448. /**
  31449. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31450. * It has no effect at all on other shapes.
  31451. * It reactivates the mesh normals computation if it was previously frozen.
  31452. * Returns the Mesh.
  31453. */
  31454. Mesh.prototype.unfreezeNormals = function () {
  31455. this._areNormalsFrozen = false;
  31456. return this;
  31457. };
  31458. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31459. /**
  31460. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31461. */
  31462. set: function (count) {
  31463. this._overridenInstanceCount = count;
  31464. },
  31465. enumerable: true,
  31466. configurable: true
  31467. });
  31468. // Methods
  31469. Mesh.prototype._preActivate = function () {
  31470. var sceneRenderId = this.getScene().getRenderId();
  31471. if (this._preActivateId === sceneRenderId) {
  31472. return this;
  31473. }
  31474. this._preActivateId = sceneRenderId;
  31475. this._visibleInstances = null;
  31476. return this;
  31477. };
  31478. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31479. if (this._visibleInstances) {
  31480. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31481. }
  31482. return this;
  31483. };
  31484. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31485. if (!this._visibleInstances) {
  31486. this._visibleInstances = {};
  31487. this._visibleInstances.defaultRenderId = renderId;
  31488. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31489. }
  31490. if (!this._visibleInstances[renderId]) {
  31491. this._visibleInstances[renderId] = new Array();
  31492. }
  31493. this._visibleInstances[renderId].push(instance);
  31494. return this;
  31495. };
  31496. /**
  31497. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31498. * This means the mesh underlying bounding box and sphere are recomputed.
  31499. * Returns the Mesh.
  31500. */
  31501. Mesh.prototype.refreshBoundingInfo = function () {
  31502. return this._refreshBoundingInfo(false);
  31503. };
  31504. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31505. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31506. return this;
  31507. }
  31508. var data = this._getPositionData(applySkeleton);
  31509. if (data) {
  31510. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31511. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31512. }
  31513. if (this.subMeshes) {
  31514. for (var index = 0; index < this.subMeshes.length; index++) {
  31515. this.subMeshes[index].refreshBoundingInfo();
  31516. }
  31517. }
  31518. this._updateBoundingInfo();
  31519. return this;
  31520. };
  31521. Mesh.prototype._getPositionData = function (applySkeleton) {
  31522. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31523. if (data && applySkeleton && this.skeleton) {
  31524. data = BABYLON.Tools.Slice(data);
  31525. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31526. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31527. if (matricesWeightsData && matricesIndicesData) {
  31528. var needExtras = this.numBoneInfluencers > 4;
  31529. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31530. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31531. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31532. var tempVector = BABYLON.Tmp.Vector3[0];
  31533. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31534. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31535. var matWeightIdx = 0;
  31536. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31537. finalMatrix.reset();
  31538. var inf;
  31539. var weight;
  31540. for (inf = 0; inf < 4; inf++) {
  31541. weight = matricesWeightsData[matWeightIdx + inf];
  31542. if (weight > 0) {
  31543. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31544. finalMatrix.addToSelf(tempMatrix);
  31545. }
  31546. }
  31547. if (needExtras) {
  31548. for (inf = 0; inf < 4; inf++) {
  31549. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31550. if (weight > 0) {
  31551. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31552. finalMatrix.addToSelf(tempMatrix);
  31553. }
  31554. }
  31555. }
  31556. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31557. tempVector.toArray(data, index);
  31558. }
  31559. }
  31560. }
  31561. return data;
  31562. };
  31563. Mesh.prototype._createGlobalSubMesh = function (force) {
  31564. var totalVertices = this.getTotalVertices();
  31565. if (!totalVertices || !this.getIndices()) {
  31566. return null;
  31567. }
  31568. // Check if we need to recreate the submeshes
  31569. if (this.subMeshes && this.subMeshes.length > 0) {
  31570. var ib = this.getIndices();
  31571. if (!ib) {
  31572. return null;
  31573. }
  31574. var totalIndices = ib.length;
  31575. var needToRecreate = false;
  31576. if (force) {
  31577. needToRecreate = true;
  31578. }
  31579. else {
  31580. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31581. var submesh = _a[_i];
  31582. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31583. needToRecreate = true;
  31584. break;
  31585. }
  31586. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31587. needToRecreate = true;
  31588. break;
  31589. }
  31590. }
  31591. }
  31592. if (!needToRecreate) {
  31593. return this.subMeshes[0];
  31594. }
  31595. }
  31596. this.releaseSubMeshes();
  31597. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31598. };
  31599. Mesh.prototype.subdivide = function (count) {
  31600. if (count < 1) {
  31601. return;
  31602. }
  31603. var totalIndices = this.getTotalIndices();
  31604. var subdivisionSize = (totalIndices / count) | 0;
  31605. var offset = 0;
  31606. // Ensure that subdivisionSize is a multiple of 3
  31607. while (subdivisionSize % 3 !== 0) {
  31608. subdivisionSize++;
  31609. }
  31610. this.releaseSubMeshes();
  31611. for (var index = 0; index < count; index++) {
  31612. if (offset >= totalIndices) {
  31613. break;
  31614. }
  31615. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31616. offset += subdivisionSize;
  31617. }
  31618. this.synchronizeInstances();
  31619. };
  31620. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31621. if (updatable === void 0) { updatable = false; }
  31622. if (!this._geometry) {
  31623. var vertexData = new BABYLON.VertexData();
  31624. vertexData.set(data, kind);
  31625. var scene = this.getScene();
  31626. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31627. }
  31628. else {
  31629. this._geometry.setVerticesData(kind, data, updatable, stride);
  31630. }
  31631. return this;
  31632. };
  31633. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31634. if (updatable === void 0) { updatable = true; }
  31635. var vb = this.getVertexBuffer(kind);
  31636. if (!vb || vb.isUpdatable() === updatable) {
  31637. return;
  31638. }
  31639. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31640. };
  31641. /**
  31642. * Sets the mesh VertexBuffer.
  31643. * Returns the Mesh.
  31644. */
  31645. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31646. if (!this._geometry) {
  31647. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31648. }
  31649. this._geometry.setVerticesBuffer(buffer);
  31650. return this;
  31651. };
  31652. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31653. if (!this._geometry) {
  31654. return this;
  31655. }
  31656. if (!makeItUnique) {
  31657. this._geometry.updateVerticesData(kind, data, updateExtends);
  31658. }
  31659. else {
  31660. this.makeGeometryUnique();
  31661. this.updateVerticesData(kind, data, updateExtends, false);
  31662. }
  31663. return this;
  31664. };
  31665. /**
  31666. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31667. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31668. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31669. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31670. * Returns the Mesh.
  31671. */
  31672. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31673. if (computeNormals === void 0) { computeNormals = true; }
  31674. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31675. if (!positions) {
  31676. return this;
  31677. }
  31678. positionFunction(positions);
  31679. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31680. if (computeNormals) {
  31681. var indices = this.getIndices();
  31682. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31683. if (!normals) {
  31684. return this;
  31685. }
  31686. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31687. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31688. }
  31689. return this;
  31690. };
  31691. /**
  31692. * Creates a un-shared specific occurence of the geometry for the mesh.
  31693. * Returns the Mesh.
  31694. */
  31695. Mesh.prototype.makeGeometryUnique = function () {
  31696. if (!this._geometry) {
  31697. return this;
  31698. }
  31699. var oldGeometry = this._geometry;
  31700. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31701. oldGeometry.releaseForMesh(this, true);
  31702. geometry.applyToMesh(this);
  31703. return this;
  31704. };
  31705. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31706. if (totalVertices === void 0) { totalVertices = null; }
  31707. if (updatable === void 0) { updatable = false; }
  31708. if (!this._geometry) {
  31709. var vertexData = new BABYLON.VertexData();
  31710. vertexData.indices = indices;
  31711. var scene = this.getScene();
  31712. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31713. }
  31714. else {
  31715. this._geometry.setIndices(indices, totalVertices, updatable);
  31716. }
  31717. return this;
  31718. };
  31719. /**
  31720. * Update the current index buffer
  31721. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31722. * Returns the Mesh.
  31723. */
  31724. Mesh.prototype.updateIndices = function (indices, offset) {
  31725. if (!this._geometry) {
  31726. return this;
  31727. }
  31728. this._geometry.updateIndices(indices, offset);
  31729. return this;
  31730. };
  31731. /**
  31732. * Invert the geometry to move from a right handed system to a left handed one.
  31733. * Returns the Mesh.
  31734. */
  31735. Mesh.prototype.toLeftHanded = function () {
  31736. if (!this._geometry) {
  31737. return this;
  31738. }
  31739. this._geometry.toLeftHanded();
  31740. return this;
  31741. };
  31742. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31743. if (!this._geometry) {
  31744. return this;
  31745. }
  31746. var engine = this.getScene().getEngine();
  31747. // Wireframe
  31748. var indexToBind;
  31749. if (this._unIndexed) {
  31750. indexToBind = null;
  31751. }
  31752. else {
  31753. switch (fillMode) {
  31754. case BABYLON.Material.PointFillMode:
  31755. indexToBind = null;
  31756. break;
  31757. case BABYLON.Material.WireFrameFillMode:
  31758. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31759. break;
  31760. default:
  31761. case BABYLON.Material.TriangleFillMode:
  31762. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31763. break;
  31764. }
  31765. }
  31766. // VBOs
  31767. this._geometry._bind(effect, indexToBind);
  31768. return this;
  31769. };
  31770. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31771. if (alternate === void 0) { alternate = false; }
  31772. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31773. return this;
  31774. }
  31775. this.onBeforeDrawObservable.notifyObservers(this);
  31776. var scene = this.getScene();
  31777. var engine = scene.getEngine();
  31778. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31779. // or triangles as points
  31780. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31781. }
  31782. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31783. // Triangles as wireframe
  31784. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31785. }
  31786. else {
  31787. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31788. }
  31789. if (scene._isAlternateRenderingEnabled && !alternate) {
  31790. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31791. if (!effect || !scene.activeCamera) {
  31792. return this;
  31793. }
  31794. scene._switchToAlternateCameraConfiguration(true);
  31795. this._effectiveMaterial.bindView(effect);
  31796. this._effectiveMaterial.bindViewProjection(effect);
  31797. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31798. this._draw(subMesh, fillMode, instancesCount, true);
  31799. engine.setViewport(scene.activeCamera.viewport);
  31800. scene._switchToAlternateCameraConfiguration(false);
  31801. this._effectiveMaterial.bindView(effect);
  31802. this._effectiveMaterial.bindViewProjection(effect);
  31803. }
  31804. return this;
  31805. };
  31806. /**
  31807. * Registers for this mesh a javascript function called just before the rendering process.
  31808. * This function is passed the current mesh.
  31809. * Return the Mesh.
  31810. */
  31811. Mesh.prototype.registerBeforeRender = function (func) {
  31812. this.onBeforeRenderObservable.add(func);
  31813. return this;
  31814. };
  31815. /**
  31816. * Disposes a previously registered javascript function called before the rendering.
  31817. * This function is passed the current mesh.
  31818. * Returns the Mesh.
  31819. */
  31820. Mesh.prototype.unregisterBeforeRender = function (func) {
  31821. this.onBeforeRenderObservable.removeCallback(func);
  31822. return this;
  31823. };
  31824. /**
  31825. * Registers for this mesh a javascript function called just after the rendering is complete.
  31826. * This function is passed the current mesh.
  31827. * Returns the Mesh.
  31828. */
  31829. Mesh.prototype.registerAfterRender = function (func) {
  31830. this.onAfterRenderObservable.add(func);
  31831. return this;
  31832. };
  31833. /**
  31834. * Disposes a previously registered javascript function called after the rendering.
  31835. * This function is passed the current mesh.
  31836. * Return the Mesh.
  31837. */
  31838. Mesh.prototype.unregisterAfterRender = function (func) {
  31839. this.onAfterRenderObservable.removeCallback(func);
  31840. return this;
  31841. };
  31842. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31843. var scene = this.getScene();
  31844. this._batchCache.mustReturn = false;
  31845. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31846. this._batchCache.visibleInstances[subMeshId] = null;
  31847. if (this._visibleInstances) {
  31848. var currentRenderId = scene.getRenderId();
  31849. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31850. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31851. var selfRenderId = this._renderId;
  31852. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31853. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31854. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31855. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31856. }
  31857. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31858. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31859. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31860. this._batchCache.mustReturn = true;
  31861. return this._batchCache;
  31862. }
  31863. if (currentRenderId !== selfRenderId) {
  31864. this._batchCache.renderSelf[subMeshId] = false;
  31865. }
  31866. }
  31867. this._renderIdForInstances[subMeshId] = currentRenderId;
  31868. }
  31869. return this._batchCache;
  31870. };
  31871. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31872. var visibleInstances = batch.visibleInstances[subMesh._id];
  31873. if (!visibleInstances) {
  31874. return this;
  31875. }
  31876. var matricesCount = visibleInstances.length + 1;
  31877. var bufferSize = matricesCount * 16 * 4;
  31878. var currentInstancesBufferSize = this._instancesBufferSize;
  31879. var instancesBuffer = this._instancesBuffer;
  31880. while (this._instancesBufferSize < bufferSize) {
  31881. this._instancesBufferSize *= 2;
  31882. }
  31883. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31884. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31885. }
  31886. var offset = 0;
  31887. var instancesCount = 0;
  31888. var world = this.getWorldMatrix();
  31889. if (batch.renderSelf[subMesh._id]) {
  31890. world.copyToArray(this._instancesData, offset);
  31891. offset += 16;
  31892. instancesCount++;
  31893. }
  31894. if (visibleInstances) {
  31895. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31896. var instance = visibleInstances[instanceIndex];
  31897. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31898. offset += 16;
  31899. instancesCount++;
  31900. }
  31901. }
  31902. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31903. if (instancesBuffer) {
  31904. instancesBuffer.dispose();
  31905. }
  31906. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31907. this._instancesBuffer = instancesBuffer;
  31908. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31909. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31910. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31911. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31912. }
  31913. else {
  31914. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31915. }
  31916. this._bind(subMesh, effect, fillMode);
  31917. this._draw(subMesh, fillMode, instancesCount);
  31918. engine.unbindInstanceAttributes();
  31919. return this;
  31920. };
  31921. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31922. var scene = this.getScene();
  31923. var engine = scene.getEngine();
  31924. if (hardwareInstancedRendering) {
  31925. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31926. }
  31927. else {
  31928. if (batch.renderSelf[subMesh._id]) {
  31929. // Draw
  31930. if (onBeforeDraw) {
  31931. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31932. }
  31933. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31934. }
  31935. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31936. if (visibleInstancesForSubMesh) {
  31937. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31938. var instance = visibleInstancesForSubMesh[instanceIndex];
  31939. // World
  31940. var world = instance.getWorldMatrix();
  31941. if (onBeforeDraw) {
  31942. onBeforeDraw(true, world, effectiveMaterial);
  31943. }
  31944. // Draw
  31945. this._draw(subMesh, fillMode);
  31946. }
  31947. }
  31948. }
  31949. return this;
  31950. };
  31951. /**
  31952. * 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
  31953. * @param subMesh defines the subMesh to render
  31954. * @param enableAlphaMode defines if alpha mode can be changed
  31955. * @returns the current mesh
  31956. */
  31957. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31958. this._checkOcclusionQuery();
  31959. if (this._isOccluded) {
  31960. return this;
  31961. }
  31962. var scene = this.getScene();
  31963. // Managing instances
  31964. var batch = this._getInstancesRenderList(subMesh._id);
  31965. if (batch.mustReturn) {
  31966. return this;
  31967. }
  31968. // Checking geometry state
  31969. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31970. return this;
  31971. }
  31972. this.onBeforeRenderObservable.notifyObservers(this);
  31973. var engine = scene.getEngine();
  31974. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31975. // Material
  31976. var material = subMesh.getMaterial();
  31977. if (!material) {
  31978. return this;
  31979. }
  31980. this._effectiveMaterial = material;
  31981. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31982. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31983. return this;
  31984. }
  31985. }
  31986. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31987. return this;
  31988. }
  31989. // Alpha mode
  31990. if (enableAlphaMode) {
  31991. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31992. }
  31993. // Outline - step 1
  31994. var savedDepthWrite = engine.getDepthWrite();
  31995. if (this.renderOutline) {
  31996. engine.setDepthWrite(false);
  31997. scene.getOutlineRenderer().render(subMesh, batch);
  31998. engine.setDepthWrite(savedDepthWrite);
  31999. }
  32000. var effect;
  32001. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32002. effect = subMesh.effect;
  32003. }
  32004. else {
  32005. effect = this._effectiveMaterial.getEffect();
  32006. }
  32007. if (!effect) {
  32008. return this;
  32009. }
  32010. var sideOrientation = this.overrideMaterialSideOrientation;
  32011. if (sideOrientation == null) {
  32012. sideOrientation = this._effectiveMaterial.sideOrientation;
  32013. if (this._getWorldMatrixDeterminant() < 0) {
  32014. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32015. }
  32016. }
  32017. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32018. if (this._effectiveMaterial.forceDepthWrite) {
  32019. engine.setDepthWrite(true);
  32020. }
  32021. // Bind
  32022. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32023. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32024. this._bind(subMesh, effect, fillMode);
  32025. }
  32026. var world = this.getWorldMatrix();
  32027. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32028. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32029. }
  32030. else {
  32031. this._effectiveMaterial.bind(world, this);
  32032. }
  32033. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32034. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32035. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32036. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32037. }
  32038. // Draw
  32039. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32040. // Unbind
  32041. this._effectiveMaterial.unbind();
  32042. // Outline - step 2
  32043. if (this.renderOutline && savedDepthWrite) {
  32044. engine.setDepthWrite(true);
  32045. engine.setColorWrite(false);
  32046. scene.getOutlineRenderer().render(subMesh, batch);
  32047. engine.setColorWrite(true);
  32048. }
  32049. // Overlay
  32050. if (this.renderOverlay) {
  32051. var currentMode = engine.getAlphaMode();
  32052. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32053. scene.getOutlineRenderer().render(subMesh, batch, true);
  32054. engine.setAlphaMode(currentMode);
  32055. }
  32056. this.onAfterRenderObservable.notifyObservers(this);
  32057. return this;
  32058. };
  32059. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32060. if (isInstance && effectiveMaterial) {
  32061. effectiveMaterial.bindOnlyWorldMatrix(world);
  32062. }
  32063. };
  32064. /**
  32065. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32066. */
  32067. Mesh.prototype.getEmittedParticleSystems = function () {
  32068. var results = new Array();
  32069. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32070. var particleSystem = this.getScene().particleSystems[index];
  32071. if (particleSystem.emitter === this) {
  32072. results.push(particleSystem);
  32073. }
  32074. }
  32075. return results;
  32076. };
  32077. /**
  32078. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32079. */
  32080. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32081. var results = new Array();
  32082. var descendants = this.getDescendants();
  32083. descendants.push(this);
  32084. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32085. var particleSystem = this.getScene().particleSystems[index];
  32086. var emitter = particleSystem.emitter;
  32087. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32088. results.push(particleSystem);
  32089. }
  32090. }
  32091. return results;
  32092. };
  32093. /**
  32094. * Normalize matrix weights so that all vertices have a total weight set to 1
  32095. */
  32096. Mesh.prototype.cleanMatrixWeights = function () {
  32097. var epsilon = 1e-3;
  32098. var noInfluenceBoneIndex = 0.0;
  32099. if (this.skeleton) {
  32100. noInfluenceBoneIndex = this.skeleton.bones.length;
  32101. }
  32102. else {
  32103. return;
  32104. }
  32105. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32106. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32107. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32108. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32109. var influencers = this.numBoneInfluencers;
  32110. var size = matricesWeights.length;
  32111. for (var i = 0; i < size; i += 4) {
  32112. var weight = 0.0;
  32113. var firstZeroWeight = -1;
  32114. for (var j = 0; j < 4; j++) {
  32115. var w = matricesWeights[i + j];
  32116. weight += w;
  32117. if (w < epsilon && firstZeroWeight < 0) {
  32118. firstZeroWeight = j;
  32119. }
  32120. }
  32121. if (matricesWeightsExtra) {
  32122. for (var j = 0; j < 4; j++) {
  32123. var w = matricesWeightsExtra[i + j];
  32124. weight += w;
  32125. if (w < epsilon && firstZeroWeight < 0) {
  32126. firstZeroWeight = j + 4;
  32127. }
  32128. }
  32129. }
  32130. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32131. firstZeroWeight = influencers - 1;
  32132. }
  32133. if (weight > epsilon) {
  32134. var mweight = 1.0 / weight;
  32135. for (var j = 0; j < 4; j++) {
  32136. matricesWeights[i + j] *= mweight;
  32137. }
  32138. if (matricesWeightsExtra) {
  32139. for (var j = 0; j < 4; j++) {
  32140. matricesWeightsExtra[i + j] *= mweight;
  32141. }
  32142. }
  32143. }
  32144. else {
  32145. if (firstZeroWeight >= 4) {
  32146. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32147. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32148. }
  32149. else {
  32150. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32151. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32152. }
  32153. }
  32154. }
  32155. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32156. if (matricesIndicesExtra) {
  32157. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32158. }
  32159. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32160. if (matricesWeightsExtra) {
  32161. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32162. }
  32163. };
  32164. Mesh.prototype._checkDelayState = function () {
  32165. var scene = this.getScene();
  32166. if (this._geometry) {
  32167. this._geometry.load(scene);
  32168. }
  32169. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32170. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32171. this._queueLoad(scene);
  32172. }
  32173. return this;
  32174. };
  32175. Mesh.prototype._queueLoad = function (scene) {
  32176. var _this = this;
  32177. scene._addPendingData(this);
  32178. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32179. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32180. if (data instanceof ArrayBuffer) {
  32181. _this._delayLoadingFunction(data, _this);
  32182. }
  32183. else {
  32184. _this._delayLoadingFunction(JSON.parse(data), _this);
  32185. }
  32186. _this.instances.forEach(function (instance) {
  32187. instance._syncSubMeshes();
  32188. });
  32189. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32190. scene._removePendingData(_this);
  32191. }, function () { }, scene.database, getBinaryData);
  32192. return this;
  32193. };
  32194. /**
  32195. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32196. */
  32197. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32198. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32199. return false;
  32200. }
  32201. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32202. return false;
  32203. }
  32204. this._checkDelayState();
  32205. return true;
  32206. };
  32207. /**
  32208. * Sets the mesh material by the material or multiMaterial `id` property.
  32209. * The material `id` is a string identifying the material or the multiMaterial.
  32210. * This method returns the Mesh.
  32211. */
  32212. Mesh.prototype.setMaterialByID = function (id) {
  32213. var materials = this.getScene().materials;
  32214. var index;
  32215. for (index = materials.length - 1; index > -1; index--) {
  32216. if (materials[index].id === id) {
  32217. this.material = materials[index];
  32218. return this;
  32219. }
  32220. }
  32221. // Multi
  32222. var multiMaterials = this.getScene().multiMaterials;
  32223. for (index = multiMaterials.length - 1; index > -1; index--) {
  32224. if (multiMaterials[index].id === id) {
  32225. this.material = multiMaterials[index];
  32226. return this;
  32227. }
  32228. }
  32229. return this;
  32230. };
  32231. /**
  32232. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32233. */
  32234. Mesh.prototype.getAnimatables = function () {
  32235. var results = new Array();
  32236. if (this.material) {
  32237. results.push(this.material);
  32238. }
  32239. if (this.skeleton) {
  32240. results.push(this.skeleton);
  32241. }
  32242. return results;
  32243. };
  32244. /**
  32245. * Modifies the mesh geometry according to the passed transformation matrix.
  32246. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32247. * The mesh normals are modified accordingly the same transformation.
  32248. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32249. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32250. * Returns the Mesh.
  32251. */
  32252. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32253. // Position
  32254. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32255. return this;
  32256. }
  32257. var submeshes = this.subMeshes.splice(0);
  32258. this._resetPointsArrayCache();
  32259. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32260. var temp = new Array();
  32261. var index;
  32262. for (index = 0; index < data.length; index += 3) {
  32263. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32264. }
  32265. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32266. // Normals
  32267. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32268. return this;
  32269. }
  32270. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32271. temp = [];
  32272. for (index = 0; index < data.length; index += 3) {
  32273. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32274. }
  32275. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32276. // flip faces?
  32277. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32278. this.flipFaces();
  32279. }
  32280. // Restore submeshes
  32281. this.releaseSubMeshes();
  32282. this.subMeshes = submeshes;
  32283. return this;
  32284. };
  32285. /**
  32286. * Modifies the mesh geometry according to its own current World Matrix.
  32287. * The mesh World Matrix is then reset.
  32288. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32289. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32290. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32291. * Returns the Mesh.
  32292. */
  32293. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32294. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32295. this.scaling.copyFromFloats(1, 1, 1);
  32296. this.position.copyFromFloats(0, 0, 0);
  32297. this.rotation.copyFromFloats(0, 0, 0);
  32298. //only if quaternion is already set
  32299. if (this.rotationQuaternion) {
  32300. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32301. }
  32302. this._worldMatrix = BABYLON.Matrix.Identity();
  32303. return this;
  32304. };
  32305. Object.defineProperty(Mesh.prototype, "_positions", {
  32306. // Cache
  32307. get: function () {
  32308. if (this._geometry) {
  32309. return this._geometry._positions;
  32310. }
  32311. return null;
  32312. },
  32313. enumerable: true,
  32314. configurable: true
  32315. });
  32316. Mesh.prototype._resetPointsArrayCache = function () {
  32317. if (this._geometry) {
  32318. this._geometry._resetPointsArrayCache();
  32319. }
  32320. return this;
  32321. };
  32322. Mesh.prototype._generatePointsArray = function () {
  32323. if (this._geometry) {
  32324. return this._geometry._generatePointsArray();
  32325. }
  32326. return false;
  32327. };
  32328. /**
  32329. * Returns a new Mesh object generated from the current mesh properties.
  32330. * This method must not get confused with createInstance().
  32331. * The parameter `name` is a string, the name given to the new mesh.
  32332. * The optional parameter `newParent` can be any Node object (default `null`).
  32333. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32334. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32335. */
  32336. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32337. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32338. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32339. };
  32340. /**
  32341. * Releases resources associated with this mesh.
  32342. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32343. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32344. */
  32345. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32346. var _this = this;
  32347. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32348. this.morphTargetManager = null;
  32349. if (this._geometry) {
  32350. this._geometry.releaseForMesh(this, true);
  32351. }
  32352. // Sources
  32353. var meshes = this.getScene().meshes;
  32354. meshes.forEach(function (abstractMesh) {
  32355. var mesh = abstractMesh;
  32356. if (mesh._source && mesh._source === _this) {
  32357. mesh._source = null;
  32358. }
  32359. });
  32360. this._source = null;
  32361. // Instances
  32362. if (this._instancesBuffer) {
  32363. this._instancesBuffer.dispose();
  32364. this._instancesBuffer = null;
  32365. }
  32366. while (this.instances.length) {
  32367. this.instances[0].dispose();
  32368. }
  32369. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32370. };
  32371. /**
  32372. * Modifies the mesh geometry according to a displacement map.
  32373. * 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.
  32374. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32375. * This method returns nothing.
  32376. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32377. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32378. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32379. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32380. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32381. *
  32382. * Returns the Mesh.
  32383. */
  32384. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32385. var _this = this;
  32386. var scene = this.getScene();
  32387. var onload = function (img) {
  32388. // Getting height map data
  32389. var canvas = document.createElement("canvas");
  32390. var context = canvas.getContext("2d");
  32391. var heightMapWidth = img.width;
  32392. var heightMapHeight = img.height;
  32393. canvas.width = heightMapWidth;
  32394. canvas.height = heightMapHeight;
  32395. context.drawImage(img, 0, 0);
  32396. // Create VertexData from map data
  32397. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32398. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32399. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32400. //execute success callback, if set
  32401. if (onSuccess) {
  32402. onSuccess(_this);
  32403. }
  32404. };
  32405. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32406. return this;
  32407. };
  32408. /**
  32409. * Modifies the mesh geometry according to a displacementMap buffer.
  32410. * 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.
  32411. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32412. * This method returns nothing.
  32413. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32414. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32415. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32416. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32417. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32418. *
  32419. * Returns the Mesh.
  32420. */
  32421. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32422. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32423. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32424. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32425. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32426. return this;
  32427. }
  32428. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32429. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32430. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32431. var position = BABYLON.Vector3.Zero();
  32432. var normal = BABYLON.Vector3.Zero();
  32433. var uv = BABYLON.Vector2.Zero();
  32434. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32435. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32436. for (var index = 0; index < positions.length; index += 3) {
  32437. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32438. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32439. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32440. // Compute height
  32441. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32442. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32443. var pos = (u + v * heightMapWidth) * 4;
  32444. var r = buffer[pos] / 255.0;
  32445. var g = buffer[pos + 1] / 255.0;
  32446. var b = buffer[pos + 2] / 255.0;
  32447. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32448. normal.normalize();
  32449. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32450. position = position.add(normal);
  32451. position.toArray(positions, index);
  32452. }
  32453. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32454. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32455. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32456. return this;
  32457. };
  32458. /**
  32459. * Modify the mesh to get a flat shading rendering.
  32460. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32461. * This method returns the Mesh.
  32462. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32463. */
  32464. Mesh.prototype.convertToFlatShadedMesh = function () {
  32465. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32466. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32467. var kinds = this.getVerticesDataKinds();
  32468. var vbs = {};
  32469. var data = {};
  32470. var newdata = {};
  32471. var updatableNormals = false;
  32472. var kindIndex;
  32473. var kind;
  32474. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32475. kind = kinds[kindIndex];
  32476. var vertexBuffer = this.getVertexBuffer(kind);
  32477. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32478. updatableNormals = vertexBuffer.isUpdatable();
  32479. kinds.splice(kindIndex, 1);
  32480. kindIndex--;
  32481. continue;
  32482. }
  32483. vbs[kind] = vertexBuffer;
  32484. data[kind] = vbs[kind].getData();
  32485. newdata[kind] = [];
  32486. }
  32487. // Save previous submeshes
  32488. var previousSubmeshes = this.subMeshes.slice(0);
  32489. var indices = this.getIndices();
  32490. var totalIndices = this.getTotalIndices();
  32491. // Generating unique vertices per face
  32492. var index;
  32493. for (index = 0; index < totalIndices; index++) {
  32494. var vertexIndex = indices[index];
  32495. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32496. kind = kinds[kindIndex];
  32497. var stride = vbs[kind].getStrideSize();
  32498. for (var offset = 0; offset < stride; offset++) {
  32499. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32500. }
  32501. }
  32502. }
  32503. // Updating faces & normal
  32504. var normals = [];
  32505. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32506. for (index = 0; index < totalIndices; index += 3) {
  32507. indices[index] = index;
  32508. indices[index + 1] = index + 1;
  32509. indices[index + 2] = index + 2;
  32510. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32511. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32512. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32513. var p1p2 = p1.subtract(p2);
  32514. var p3p2 = p3.subtract(p2);
  32515. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32516. // Store same normals for every vertex
  32517. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32518. normals.push(normal.x);
  32519. normals.push(normal.y);
  32520. normals.push(normal.z);
  32521. }
  32522. }
  32523. this.setIndices(indices);
  32524. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32525. // Updating vertex buffers
  32526. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32527. kind = kinds[kindIndex];
  32528. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32529. }
  32530. // Updating submeshes
  32531. this.releaseSubMeshes();
  32532. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32533. var previousOne = previousSubmeshes[submeshIndex];
  32534. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32535. }
  32536. this.synchronizeInstances();
  32537. return this;
  32538. };
  32539. /**
  32540. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32541. * In other words, more vertices, no more indices and a single bigger VBO.
  32542. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32543. * Returns the Mesh.
  32544. */
  32545. Mesh.prototype.convertToUnIndexedMesh = function () {
  32546. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32547. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32548. var kinds = this.getVerticesDataKinds();
  32549. var vbs = {};
  32550. var data = {};
  32551. var newdata = {};
  32552. var kindIndex;
  32553. var kind;
  32554. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32555. kind = kinds[kindIndex];
  32556. var vertexBuffer = this.getVertexBuffer(kind);
  32557. vbs[kind] = vertexBuffer;
  32558. data[kind] = vbs[kind].getData();
  32559. newdata[kind] = [];
  32560. }
  32561. // Save previous submeshes
  32562. var previousSubmeshes = this.subMeshes.slice(0);
  32563. var indices = this.getIndices();
  32564. var totalIndices = this.getTotalIndices();
  32565. // Generating unique vertices per face
  32566. var index;
  32567. for (index = 0; index < totalIndices; index++) {
  32568. var vertexIndex = indices[index];
  32569. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32570. kind = kinds[kindIndex];
  32571. var stride = vbs[kind].getStrideSize();
  32572. for (var offset = 0; offset < stride; offset++) {
  32573. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32574. }
  32575. }
  32576. }
  32577. // Updating indices
  32578. for (index = 0; index < totalIndices; index += 3) {
  32579. indices[index] = index;
  32580. indices[index + 1] = index + 1;
  32581. indices[index + 2] = index + 2;
  32582. }
  32583. this.setIndices(indices);
  32584. // Updating vertex buffers
  32585. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32586. kind = kinds[kindIndex];
  32587. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32588. }
  32589. // Updating submeshes
  32590. this.releaseSubMeshes();
  32591. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32592. var previousOne = previousSubmeshes[submeshIndex];
  32593. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32594. }
  32595. this._unIndexed = true;
  32596. this.synchronizeInstances();
  32597. return this;
  32598. };
  32599. /**
  32600. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32601. * This method returns the Mesh.
  32602. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32603. */
  32604. Mesh.prototype.flipFaces = function (flipNormals) {
  32605. if (flipNormals === void 0) { flipNormals = false; }
  32606. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32607. var i;
  32608. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32609. for (i = 0; i < vertex_data.normals.length; i++) {
  32610. vertex_data.normals[i] *= -1;
  32611. }
  32612. }
  32613. if (vertex_data.indices) {
  32614. var temp;
  32615. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32616. // reassign indices
  32617. temp = vertex_data.indices[i + 1];
  32618. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32619. vertex_data.indices[i + 2] = temp;
  32620. }
  32621. }
  32622. vertex_data.applyToMesh(this);
  32623. return this;
  32624. };
  32625. // Instances
  32626. /**
  32627. * Creates a new InstancedMesh object from the mesh model.
  32628. * An instance shares the same properties and the same material than its model.
  32629. * Only these properties of each instance can then be set individually :
  32630. * - position
  32631. * - rotation
  32632. * - rotationQuaternion
  32633. * - setPivotMatrix
  32634. * - scaling
  32635. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32636. * Warning : this method is not supported for Line mesh and LineSystem
  32637. */
  32638. Mesh.prototype.createInstance = function (name) {
  32639. return new BABYLON.InstancedMesh(name, this);
  32640. };
  32641. /**
  32642. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32643. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32644. * This method returns the Mesh.
  32645. */
  32646. Mesh.prototype.synchronizeInstances = function () {
  32647. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32648. var instance = this.instances[instanceIndex];
  32649. instance._syncSubMeshes();
  32650. }
  32651. return this;
  32652. };
  32653. /**
  32654. * Simplify the mesh according to the given array of settings.
  32655. * Function will return immediately and will simplify async. It returns the Mesh.
  32656. * @param settings a collection of simplification settings.
  32657. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32658. * @param type the type of simplification to run.
  32659. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32660. */
  32661. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32662. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32663. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32664. this.getScene().simplificationQueue.addTask({
  32665. settings: settings,
  32666. parallelProcessing: parallelProcessing,
  32667. mesh: this,
  32668. simplificationType: simplificationType,
  32669. successCallback: successCallback
  32670. });
  32671. return this;
  32672. };
  32673. /**
  32674. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32675. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32676. * This should be used together with the simplification to avoid disappearing triangles.
  32677. * Returns the Mesh.
  32678. * @param successCallback an optional success callback to be called after the optimization finished.
  32679. */
  32680. Mesh.prototype.optimizeIndices = function (successCallback) {
  32681. var _this = this;
  32682. var indices = this.getIndices();
  32683. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32684. if (!positions || !indices) {
  32685. return this;
  32686. }
  32687. var vectorPositions = new Array();
  32688. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32689. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32690. }
  32691. var dupes = new Array();
  32692. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32693. var realPos = vectorPositions.length - 1 - iteration;
  32694. var testedPosition = vectorPositions[realPos];
  32695. for (var j = 0; j < realPos; ++j) {
  32696. var againstPosition = vectorPositions[j];
  32697. if (testedPosition.equals(againstPosition)) {
  32698. dupes[realPos] = j;
  32699. break;
  32700. }
  32701. }
  32702. }, function () {
  32703. for (var i = 0; i < indices.length; ++i) {
  32704. indices[i] = dupes[indices[i]] || indices[i];
  32705. }
  32706. //indices are now reordered
  32707. var originalSubMeshes = _this.subMeshes.slice(0);
  32708. _this.setIndices(indices);
  32709. _this.subMeshes = originalSubMeshes;
  32710. if (successCallback) {
  32711. successCallback(_this);
  32712. }
  32713. });
  32714. return this;
  32715. };
  32716. Mesh.prototype.serialize = function (serializationObject) {
  32717. serializationObject.name = this.name;
  32718. serializationObject.id = this.id;
  32719. serializationObject.type = this.getClassName();
  32720. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32721. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32722. }
  32723. serializationObject.position = this.position.asArray();
  32724. if (this.rotationQuaternion) {
  32725. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32726. }
  32727. else if (this.rotation) {
  32728. serializationObject.rotation = this.rotation.asArray();
  32729. }
  32730. serializationObject.scaling = this.scaling.asArray();
  32731. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32732. serializationObject.isEnabled = this.isEnabled(false);
  32733. serializationObject.isVisible = this.isVisible;
  32734. serializationObject.infiniteDistance = this.infiniteDistance;
  32735. serializationObject.pickable = this.isPickable;
  32736. serializationObject.receiveShadows = this.receiveShadows;
  32737. serializationObject.billboardMode = this.billboardMode;
  32738. serializationObject.visibility = this.visibility;
  32739. serializationObject.checkCollisions = this.checkCollisions;
  32740. serializationObject.isBlocker = this.isBlocker;
  32741. // Parent
  32742. if (this.parent) {
  32743. serializationObject.parentId = this.parent.id;
  32744. }
  32745. // Geometry
  32746. serializationObject.isUnIndexed = this.isUnIndexed;
  32747. var geometry = this._geometry;
  32748. if (geometry) {
  32749. var geometryId = geometry.id;
  32750. serializationObject.geometryId = geometryId;
  32751. // SubMeshes
  32752. serializationObject.subMeshes = [];
  32753. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32754. var subMesh = this.subMeshes[subIndex];
  32755. serializationObject.subMeshes.push({
  32756. materialIndex: subMesh.materialIndex,
  32757. verticesStart: subMesh.verticesStart,
  32758. verticesCount: subMesh.verticesCount,
  32759. indexStart: subMesh.indexStart,
  32760. indexCount: subMesh.indexCount
  32761. });
  32762. }
  32763. }
  32764. // Material
  32765. if (this.material) {
  32766. serializationObject.materialId = this.material.id;
  32767. }
  32768. else {
  32769. this.material = null;
  32770. }
  32771. // Morph targets
  32772. if (this.morphTargetManager) {
  32773. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32774. }
  32775. // Skeleton
  32776. if (this.skeleton) {
  32777. serializationObject.skeletonId = this.skeleton.id;
  32778. }
  32779. // Physics
  32780. //TODO implement correct serialization for physics impostors.
  32781. var impostor = this.getPhysicsImpostor();
  32782. if (impostor) {
  32783. serializationObject.physicsMass = impostor.getParam("mass");
  32784. serializationObject.physicsFriction = impostor.getParam("friction");
  32785. serializationObject.physicsRestitution = impostor.getParam("mass");
  32786. serializationObject.physicsImpostor = impostor.type;
  32787. }
  32788. // Metadata
  32789. if (this.metadata) {
  32790. serializationObject.metadata = this.metadata;
  32791. }
  32792. // Instances
  32793. serializationObject.instances = [];
  32794. for (var index = 0; index < this.instances.length; index++) {
  32795. var instance = this.instances[index];
  32796. var serializationInstance = {
  32797. name: instance.name,
  32798. id: instance.id,
  32799. position: instance.position.asArray(),
  32800. scaling: instance.scaling.asArray()
  32801. };
  32802. if (instance.rotationQuaternion) {
  32803. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32804. }
  32805. else if (instance.rotation) {
  32806. serializationInstance.rotation = instance.rotation.asArray();
  32807. }
  32808. serializationObject.instances.push(serializationInstance);
  32809. // Animations
  32810. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32811. serializationInstance.ranges = instance.serializeAnimationRanges();
  32812. }
  32813. //
  32814. // Animations
  32815. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32816. serializationObject.ranges = this.serializeAnimationRanges();
  32817. // Layer mask
  32818. serializationObject.layerMask = this.layerMask;
  32819. // Alpha
  32820. serializationObject.alphaIndex = this.alphaIndex;
  32821. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32822. // Overlay
  32823. serializationObject.overlayAlpha = this.overlayAlpha;
  32824. serializationObject.overlayColor = this.overlayColor.asArray();
  32825. serializationObject.renderOverlay = this.renderOverlay;
  32826. // Fog
  32827. serializationObject.applyFog = this.applyFog;
  32828. // Action Manager
  32829. if (this.actionManager) {
  32830. serializationObject.actions = this.actionManager.serialize(this.name);
  32831. }
  32832. };
  32833. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32834. if (!this.geometry) {
  32835. return;
  32836. }
  32837. this._markSubMeshesAsAttributesDirty();
  32838. var morphTargetManager = this._morphTargetManager;
  32839. if (morphTargetManager && morphTargetManager.vertexCount) {
  32840. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32841. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32842. this.morphTargetManager = null;
  32843. return;
  32844. }
  32845. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32846. var morphTarget = morphTargetManager.getActiveTarget(index);
  32847. var positions = morphTarget.getPositions();
  32848. if (!positions) {
  32849. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32850. return;
  32851. }
  32852. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32853. var normals = morphTarget.getNormals();
  32854. if (normals) {
  32855. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32856. }
  32857. var tangents = morphTarget.getTangents();
  32858. if (tangents) {
  32859. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32860. }
  32861. }
  32862. }
  32863. else {
  32864. var index = 0;
  32865. // Positions
  32866. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32867. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32868. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32869. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32870. }
  32871. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32872. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32873. }
  32874. index++;
  32875. }
  32876. }
  32877. };
  32878. // Statics
  32879. /**
  32880. * Returns a new Mesh object parsed from the source provided.
  32881. * The parameter `parsedMesh` is the source.
  32882. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32883. */
  32884. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32885. var mesh;
  32886. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32887. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32888. }
  32889. else {
  32890. mesh = new Mesh(parsedMesh.name, scene);
  32891. }
  32892. mesh.id = parsedMesh.id;
  32893. if (BABYLON.Tags) {
  32894. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32895. }
  32896. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32897. if (parsedMesh.metadata !== undefined) {
  32898. mesh.metadata = parsedMesh.metadata;
  32899. }
  32900. if (parsedMesh.rotationQuaternion) {
  32901. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32902. }
  32903. else if (parsedMesh.rotation) {
  32904. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32905. }
  32906. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32907. if (parsedMesh.localMatrix) {
  32908. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32909. }
  32910. else if (parsedMesh.pivotMatrix) {
  32911. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32912. }
  32913. mesh.setEnabled(parsedMesh.isEnabled);
  32914. mesh.isVisible = parsedMesh.isVisible;
  32915. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32916. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32917. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32918. if (parsedMesh.applyFog !== undefined) {
  32919. mesh.applyFog = parsedMesh.applyFog;
  32920. }
  32921. if (parsedMesh.pickable !== undefined) {
  32922. mesh.isPickable = parsedMesh.pickable;
  32923. }
  32924. if (parsedMesh.alphaIndex !== undefined) {
  32925. mesh.alphaIndex = parsedMesh.alphaIndex;
  32926. }
  32927. mesh.receiveShadows = parsedMesh.receiveShadows;
  32928. mesh.billboardMode = parsedMesh.billboardMode;
  32929. if (parsedMesh.visibility !== undefined) {
  32930. mesh.visibility = parsedMesh.visibility;
  32931. }
  32932. mesh.checkCollisions = parsedMesh.checkCollisions;
  32933. if (parsedMesh.isBlocker !== undefined) {
  32934. mesh.isBlocker = parsedMesh.isBlocker;
  32935. }
  32936. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32937. // freezeWorldMatrix
  32938. if (parsedMesh.freezeWorldMatrix) {
  32939. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32940. }
  32941. // Parent
  32942. if (parsedMesh.parentId) {
  32943. mesh._waitingParentId = parsedMesh.parentId;
  32944. }
  32945. // Actions
  32946. if (parsedMesh.actions !== undefined) {
  32947. mesh._waitingActions = parsedMesh.actions;
  32948. }
  32949. // Overlay
  32950. if (parsedMesh.overlayAlpha !== undefined) {
  32951. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32952. }
  32953. if (parsedMesh.overlayColor !== undefined) {
  32954. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32955. }
  32956. if (parsedMesh.renderOverlay !== undefined) {
  32957. mesh.renderOverlay = parsedMesh.renderOverlay;
  32958. }
  32959. // Geometry
  32960. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32961. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32962. if (parsedMesh.delayLoadingFile) {
  32963. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32964. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32965. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32966. if (parsedMesh._binaryInfo) {
  32967. mesh._binaryInfo = parsedMesh._binaryInfo;
  32968. }
  32969. mesh._delayInfo = [];
  32970. if (parsedMesh.hasUVs) {
  32971. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32972. }
  32973. if (parsedMesh.hasUVs2) {
  32974. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32975. }
  32976. if (parsedMesh.hasUVs3) {
  32977. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32978. }
  32979. if (parsedMesh.hasUVs4) {
  32980. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32981. }
  32982. if (parsedMesh.hasUVs5) {
  32983. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32984. }
  32985. if (parsedMesh.hasUVs6) {
  32986. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32987. }
  32988. if (parsedMesh.hasColors) {
  32989. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32990. }
  32991. if (parsedMesh.hasMatricesIndices) {
  32992. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32993. }
  32994. if (parsedMesh.hasMatricesWeights) {
  32995. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32996. }
  32997. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32998. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32999. mesh._checkDelayState();
  33000. }
  33001. }
  33002. else {
  33003. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33004. }
  33005. // Material
  33006. if (parsedMesh.materialId) {
  33007. mesh.setMaterialByID(parsedMesh.materialId);
  33008. }
  33009. else {
  33010. mesh.material = null;
  33011. }
  33012. // Morph targets
  33013. if (parsedMesh.morphTargetManagerId > -1) {
  33014. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33015. }
  33016. // Skeleton
  33017. if (parsedMesh.skeletonId > -1) {
  33018. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33019. if (parsedMesh.numBoneInfluencers) {
  33020. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33021. }
  33022. }
  33023. // Animations
  33024. if (parsedMesh.animations) {
  33025. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33026. var parsedAnimation = parsedMesh.animations[animationIndex];
  33027. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33028. }
  33029. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33030. }
  33031. if (parsedMesh.autoAnimate) {
  33032. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33033. }
  33034. // Layer Mask
  33035. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33036. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33037. }
  33038. else {
  33039. mesh.layerMask = 0x0FFFFFFF;
  33040. }
  33041. // Physics
  33042. if (parsedMesh.physicsImpostor) {
  33043. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33044. mass: parsedMesh.physicsMass,
  33045. friction: parsedMesh.physicsFriction,
  33046. restitution: parsedMesh.physicsRestitution
  33047. }, scene);
  33048. }
  33049. // Instances
  33050. if (parsedMesh.instances) {
  33051. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33052. var parsedInstance = parsedMesh.instances[index];
  33053. var instance = mesh.createInstance(parsedInstance.name);
  33054. if (parsedInstance.id) {
  33055. instance.id = parsedInstance.id;
  33056. }
  33057. if (BABYLON.Tags) {
  33058. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33059. }
  33060. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33061. if (parsedInstance.parentId) {
  33062. instance._waitingParentId = parsedInstance.parentId;
  33063. }
  33064. if (parsedInstance.rotationQuaternion) {
  33065. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33066. }
  33067. else if (parsedInstance.rotation) {
  33068. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33069. }
  33070. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33071. instance.checkCollisions = mesh.checkCollisions;
  33072. if (parsedMesh.animations) {
  33073. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33074. parsedAnimation = parsedMesh.animations[animationIndex];
  33075. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33076. }
  33077. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33078. if (parsedMesh.autoAnimate) {
  33079. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33080. }
  33081. }
  33082. }
  33083. }
  33084. return mesh;
  33085. };
  33086. /**
  33087. * Creates a ribbon mesh.
  33088. * Please consider using the same method from the MeshBuilder class instead.
  33089. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33090. *
  33091. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33092. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33093. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33094. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33095. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  33096. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33097. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  33098. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33099. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33100. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33101. */
  33102. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33103. if (closeArray === void 0) { closeArray = false; }
  33104. if (updatable === void 0) { updatable = false; }
  33105. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33106. pathArray: pathArray,
  33107. closeArray: closeArray,
  33108. closePath: closePath,
  33109. offset: offset,
  33110. updatable: updatable,
  33111. sideOrientation: sideOrientation,
  33112. instance: instance
  33113. }, scene);
  33114. };
  33115. /**
  33116. * Creates a plane polygonal mesh. By default, this is a disc.
  33117. * Please consider using the same method from the MeshBuilder class instead.
  33118. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33119. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  33120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33121. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33123. */
  33124. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33125. if (scene === void 0) { scene = null; }
  33126. var options = {
  33127. radius: radius,
  33128. tessellation: tessellation,
  33129. sideOrientation: sideOrientation,
  33130. updatable: updatable
  33131. };
  33132. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33133. };
  33134. /**
  33135. * Creates a box mesh.
  33136. * Please consider using the same method from the MeshBuilder class instead.
  33137. * The parameter `size` sets the size (float) of each box side (default 1).
  33138. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33139. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33141. */
  33142. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33143. if (scene === void 0) { scene = null; }
  33144. var options = {
  33145. size: size,
  33146. sideOrientation: sideOrientation,
  33147. updatable: updatable
  33148. };
  33149. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33150. };
  33151. /**
  33152. * Creates a sphere mesh.
  33153. * Please consider using the same method from the MeshBuilder class instead.
  33154. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33155. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33157. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33158. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33159. */
  33160. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33161. var options = {
  33162. segments: segments,
  33163. diameterX: diameter,
  33164. diameterY: diameter,
  33165. diameterZ: diameter,
  33166. sideOrientation: sideOrientation,
  33167. updatable: updatable
  33168. };
  33169. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33170. };
  33171. /**
  33172. * Creates a cylinder or a cone mesh.
  33173. * Please consider using the same method from the MeshBuilder class instead.
  33174. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33175. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33176. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  33177. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33178. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33180. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33182. */
  33183. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33184. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33185. if (scene !== undefined) {
  33186. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33187. updatable = scene;
  33188. }
  33189. scene = subdivisions;
  33190. subdivisions = 1;
  33191. }
  33192. var options = {
  33193. height: height,
  33194. diameterTop: diameterTop,
  33195. diameterBottom: diameterBottom,
  33196. tessellation: tessellation,
  33197. subdivisions: subdivisions,
  33198. sideOrientation: sideOrientation,
  33199. updatable: updatable
  33200. };
  33201. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33202. };
  33203. // Torus (Code from SharpDX.org)
  33204. /**
  33205. * Creates a torus mesh.
  33206. * Please consider using the same method from the MeshBuilder class instead.
  33207. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33208. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33209. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33210. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33211. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33213. */
  33214. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33215. var options = {
  33216. diameter: diameter,
  33217. thickness: thickness,
  33218. tessellation: tessellation,
  33219. sideOrientation: sideOrientation,
  33220. updatable: updatable
  33221. };
  33222. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33223. };
  33224. /**
  33225. * Creates a torus knot mesh.
  33226. * Please consider using the same method from the MeshBuilder class instead.
  33227. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33228. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33229. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33230. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33231. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33232. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33234. */
  33235. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33236. var options = {
  33237. radius: radius,
  33238. tube: tube,
  33239. radialSegments: radialSegments,
  33240. tubularSegments: tubularSegments,
  33241. p: p,
  33242. q: q,
  33243. sideOrientation: sideOrientation,
  33244. updatable: updatable
  33245. };
  33246. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33247. };
  33248. /**
  33249. * Creates a line mesh.
  33250. * Please consider using the same method from the MeshBuilder class instead.
  33251. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  33252. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33253. * The parameter `points` is an array successive Vector3.
  33254. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  33255. * When updating an instance, remember that only point positions can change, not the number of points.
  33256. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33257. */
  33258. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33259. if (scene === void 0) { scene = null; }
  33260. if (updatable === void 0) { updatable = false; }
  33261. if (instance === void 0) { instance = null; }
  33262. var options = {
  33263. points: points,
  33264. updatable: updatable,
  33265. instance: instance
  33266. };
  33267. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33268. };
  33269. /**
  33270. * Creates a dashed line mesh.
  33271. * Please consider using the same method from the MeshBuilder class instead.
  33272. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  33273. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33274. * The parameter `points` is an array successive Vector3.
  33275. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33276. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33277. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33278. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  33279. * When updating an instance, remember that only point positions can change, not the number of points.
  33280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33281. */
  33282. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33283. if (scene === void 0) { scene = null; }
  33284. var options = {
  33285. points: points,
  33286. dashSize: dashSize,
  33287. gapSize: gapSize,
  33288. dashNb: dashNb,
  33289. updatable: updatable,
  33290. instance: instance
  33291. };
  33292. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33293. };
  33294. /**
  33295. * Creates a polygon mesh.
  33296. * Please consider using the same method from the MeshBuilder class instead.
  33297. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33298. * 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.
  33299. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33301. * Remember you can only change the shape positions, not their number when updating a polygon.
  33302. */
  33303. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33304. var options = {
  33305. shape: shape,
  33306. holes: holes,
  33307. updatable: updatable,
  33308. sideOrientation: sideOrientation
  33309. };
  33310. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33311. };
  33312. /**
  33313. * Creates an extruded polygon mesh, with depth in the Y direction.
  33314. * Please consider using the same method from the MeshBuilder class instead.
  33315. */
  33316. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33317. var options = {
  33318. shape: shape,
  33319. holes: holes,
  33320. depth: depth,
  33321. updatable: updatable,
  33322. sideOrientation: sideOrientation
  33323. };
  33324. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33325. };
  33326. /**
  33327. * Creates an extruded shape mesh.
  33328. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33329. * Please consider using the same method from the MeshBuilder class instead.
  33330. *
  33331. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33332. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  33333. * extruded along the Z axis.
  33334. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33335. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  33336. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33337. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33338. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  33339. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33341. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33343. */
  33344. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33345. if (scene === void 0) { scene = null; }
  33346. var options = {
  33347. shape: shape,
  33348. path: path,
  33349. scale: scale,
  33350. rotation: rotation,
  33351. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33352. sideOrientation: sideOrientation,
  33353. instance: instance,
  33354. updatable: updatable
  33355. };
  33356. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33357. };
  33358. /**
  33359. * Creates an custom extruded shape mesh.
  33360. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33361. * Please consider using the same method from the MeshBuilder class instead.
  33362. *
  33363. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33364. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  33365. * extruded along the Z axis.
  33366. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33367. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  33368. * and the distance of this point from the begining of the path :
  33369. * ```javascript
  33370. * var rotationFunction = function(i, distance) {
  33371. * // do things
  33372. * return rotationValue; }
  33373. * ```
  33374. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33375. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  33376. * and the distance of this point from the begining of the path :
  33377. * ```javascript
  33378. * var scaleFunction = function(i, distance) {
  33379. * // do things
  33380. * return scaleValue;}
  33381. * ```
  33382. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33383. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33384. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33385. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33386. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  33387. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33389. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33391. */
  33392. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33393. var options = {
  33394. shape: shape,
  33395. path: path,
  33396. scaleFunction: scaleFunction,
  33397. rotationFunction: rotationFunction,
  33398. ribbonCloseArray: ribbonCloseArray,
  33399. ribbonClosePath: ribbonClosePath,
  33400. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33401. sideOrientation: sideOrientation,
  33402. instance: instance,
  33403. updatable: updatable
  33404. };
  33405. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33406. };
  33407. /**
  33408. * Creates lathe mesh.
  33409. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33410. * Please consider using the same method from the MeshBuilder class instead.
  33411. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  33412. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33413. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33414. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33415. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33416. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33418. */
  33419. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33420. var options = {
  33421. shape: shape,
  33422. radius: radius,
  33423. tessellation: tessellation,
  33424. sideOrientation: sideOrientation,
  33425. updatable: updatable
  33426. };
  33427. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33428. };
  33429. /**
  33430. * Creates a plane mesh.
  33431. * Please consider using the same method from the MeshBuilder class instead.
  33432. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33434. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33436. */
  33437. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33438. var options = {
  33439. size: size,
  33440. width: size,
  33441. height: size,
  33442. sideOrientation: sideOrientation,
  33443. updatable: updatable
  33444. };
  33445. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33446. };
  33447. /**
  33448. * Creates a ground mesh.
  33449. * Please consider using the same method from the MeshBuilder class instead.
  33450. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33451. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33453. */
  33454. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33455. var options = {
  33456. width: width,
  33457. height: height,
  33458. subdivisions: subdivisions,
  33459. updatable: updatable
  33460. };
  33461. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33462. };
  33463. /**
  33464. * Creates a tiled ground mesh.
  33465. * Please consider using the same method from the MeshBuilder class instead.
  33466. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33467. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33468. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33469. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33470. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33471. * numbers of subdivisions on the ground width and height of each tile.
  33472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33473. */
  33474. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33475. var options = {
  33476. xmin: xmin,
  33477. zmin: zmin,
  33478. xmax: xmax,
  33479. zmax: zmax,
  33480. subdivisions: subdivisions,
  33481. precision: precision,
  33482. updatable: updatable
  33483. };
  33484. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33485. };
  33486. /**
  33487. * Creates a ground mesh from a height map.
  33488. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33489. * Please consider using the same method from the MeshBuilder class instead.
  33490. * The parameter `url` sets the URL of the height map image resource.
  33491. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33492. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33493. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33494. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33495. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  33496. * This function is passed the newly built mesh :
  33497. * ```javascript
  33498. * function(mesh) { // do things
  33499. * return; }
  33500. * ```
  33501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33502. */
  33503. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33504. var options = {
  33505. width: width,
  33506. height: height,
  33507. subdivisions: subdivisions,
  33508. minHeight: minHeight,
  33509. maxHeight: maxHeight,
  33510. updatable: updatable,
  33511. onReady: onReady
  33512. };
  33513. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33514. };
  33515. /**
  33516. * Creates a tube mesh.
  33517. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33518. * Please consider using the same method from the MeshBuilder class instead.
  33519. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33520. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33521. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33522. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33523. * 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.
  33524. * It must return a radius value (positive float) :
  33525. * ```javascript
  33526. * var radiusFunction = function(i, distance) {
  33527. * // do things
  33528. * return radius; }
  33529. * ```
  33530. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33531. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  33532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33533. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33535. */
  33536. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33537. var options = {
  33538. path: path,
  33539. radius: radius,
  33540. tessellation: tessellation,
  33541. radiusFunction: radiusFunction,
  33542. arc: 1,
  33543. cap: cap,
  33544. updatable: updatable,
  33545. sideOrientation: sideOrientation,
  33546. instance: instance
  33547. };
  33548. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33549. };
  33550. /**
  33551. * Creates a polyhedron mesh.
  33552. * Please consider using the same method from the MeshBuilder class instead.
  33553. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  33554. * to choose the wanted type.
  33555. * The parameter `size` (positive float, default 1) sets the polygon size.
  33556. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33557. * 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`.
  33558. * 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
  33559. * 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)`).
  33560. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  33561. * 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.
  33562. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33563. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33565. */
  33566. Mesh.CreatePolyhedron = function (name, options, scene) {
  33567. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33568. };
  33569. /**
  33570. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33571. * Please consider using the same method from the MeshBuilder class instead.
  33572. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33573. * 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`).
  33574. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33575. * 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.
  33576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33577. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33579. */
  33580. Mesh.CreateIcoSphere = function (name, options, scene) {
  33581. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33582. };
  33583. /**
  33584. * Creates a decal mesh.
  33585. * Please consider using the same method from the MeshBuilder class instead.
  33586. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  33587. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33588. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33589. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33590. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33591. */
  33592. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33593. var options = {
  33594. position: position,
  33595. normal: normal,
  33596. size: size,
  33597. angle: angle
  33598. };
  33599. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33600. };
  33601. // Skeletons
  33602. /**
  33603. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33604. */
  33605. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33606. if (!this._sourcePositions) {
  33607. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33608. if (!source) {
  33609. return this._sourcePositions;
  33610. }
  33611. this._sourcePositions = new Float32Array(source);
  33612. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33613. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33614. }
  33615. }
  33616. return this._sourcePositions;
  33617. };
  33618. /**
  33619. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33620. */
  33621. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33622. if (!this._sourceNormals) {
  33623. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33624. if (!source) {
  33625. return this._sourceNormals;
  33626. }
  33627. this._sourceNormals = new Float32Array(source);
  33628. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33629. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33630. }
  33631. }
  33632. return this._sourceNormals;
  33633. };
  33634. /**
  33635. * Updates the vertex buffer by applying transformation from the bones.
  33636. * Returns the Mesh.
  33637. *
  33638. * @param {skeleton} skeleton to apply
  33639. */
  33640. Mesh.prototype.applySkeleton = function (skeleton) {
  33641. if (!this.geometry) {
  33642. return this;
  33643. }
  33644. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33645. return this;
  33646. }
  33647. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33648. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33649. return this;
  33650. }
  33651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33652. return this;
  33653. }
  33654. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33655. return this;
  33656. }
  33657. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33658. return this;
  33659. }
  33660. if (!this._sourcePositions) {
  33661. var submeshes = this.subMeshes.slice();
  33662. this.setPositionsForCPUSkinning();
  33663. this.subMeshes = submeshes;
  33664. }
  33665. if (!this._sourceNormals) {
  33666. this.setNormalsForCPUSkinning();
  33667. }
  33668. // positionsData checks for not being Float32Array will only pass at most once
  33669. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33670. if (!positionsData) {
  33671. return this;
  33672. }
  33673. if (!(positionsData instanceof Float32Array)) {
  33674. positionsData = new Float32Array(positionsData);
  33675. }
  33676. // normalsData checks for not being Float32Array will only pass at most once
  33677. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33678. if (!normalsData) {
  33679. return this;
  33680. }
  33681. if (!(normalsData instanceof Float32Array)) {
  33682. normalsData = new Float32Array(normalsData);
  33683. }
  33684. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33685. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33686. if (!matricesWeightsData || !matricesIndicesData) {
  33687. return this;
  33688. }
  33689. var needExtras = this.numBoneInfluencers > 4;
  33690. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33691. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33692. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33693. var tempVector3 = BABYLON.Vector3.Zero();
  33694. var finalMatrix = new BABYLON.Matrix();
  33695. var tempMatrix = new BABYLON.Matrix();
  33696. var matWeightIdx = 0;
  33697. var inf;
  33698. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33699. var weight;
  33700. for (inf = 0; inf < 4; inf++) {
  33701. weight = matricesWeightsData[matWeightIdx + inf];
  33702. if (weight > 0) {
  33703. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33704. finalMatrix.addToSelf(tempMatrix);
  33705. }
  33706. }
  33707. if (needExtras) {
  33708. for (inf = 0; inf < 4; inf++) {
  33709. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33710. if (weight > 0) {
  33711. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33712. finalMatrix.addToSelf(tempMatrix);
  33713. }
  33714. }
  33715. }
  33716. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33717. tempVector3.toArray(positionsData, index);
  33718. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33719. tempVector3.toArray(normalsData, index);
  33720. finalMatrix.reset();
  33721. }
  33722. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33723. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33724. return this;
  33725. };
  33726. // Tools
  33727. /**
  33728. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33729. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33730. */
  33731. Mesh.MinMax = function (meshes) {
  33732. var minVector = null;
  33733. var maxVector = null;
  33734. meshes.forEach(function (mesh, index, array) {
  33735. var boundingInfo = mesh.getBoundingInfo();
  33736. var boundingBox = boundingInfo.boundingBox;
  33737. if (!minVector || !maxVector) {
  33738. minVector = boundingBox.minimumWorld;
  33739. maxVector = boundingBox.maximumWorld;
  33740. }
  33741. else {
  33742. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33743. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33744. }
  33745. });
  33746. if (!minVector || !maxVector) {
  33747. return {
  33748. min: BABYLON.Vector3.Zero(),
  33749. max: BABYLON.Vector3.Zero()
  33750. };
  33751. }
  33752. return {
  33753. min: minVector,
  33754. max: maxVector
  33755. };
  33756. };
  33757. /**
  33758. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33759. */
  33760. Mesh.Center = function (meshesOrMinMaxVector) {
  33761. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33762. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33763. };
  33764. /**
  33765. * Merge the array of meshes into a single mesh for performance reasons.
  33766. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33767. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33768. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33769. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33770. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33771. */
  33772. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33773. if (disposeSource === void 0) { disposeSource = true; }
  33774. var index;
  33775. if (!allow32BitsIndices) {
  33776. var totalVertices = 0;
  33777. // Counting vertices
  33778. for (index = 0; index < meshes.length; index++) {
  33779. if (meshes[index]) {
  33780. totalVertices += meshes[index].getTotalVertices();
  33781. if (totalVertices > 65536) {
  33782. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33783. return null;
  33784. }
  33785. }
  33786. }
  33787. }
  33788. // Merge
  33789. var vertexData = null;
  33790. var otherVertexData;
  33791. var indiceArray = new Array();
  33792. var source = null;
  33793. for (index = 0; index < meshes.length; index++) {
  33794. if (meshes[index]) {
  33795. meshes[index].computeWorldMatrix(true);
  33796. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33797. otherVertexData.transform(meshes[index].getWorldMatrix());
  33798. if (vertexData) {
  33799. vertexData.merge(otherVertexData);
  33800. }
  33801. else {
  33802. vertexData = otherVertexData;
  33803. source = meshes[index];
  33804. }
  33805. if (subdivideWithSubMeshes) {
  33806. indiceArray.push(meshes[index].getTotalIndices());
  33807. }
  33808. }
  33809. }
  33810. source = source;
  33811. if (!meshSubclass) {
  33812. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33813. }
  33814. vertexData.applyToMesh(meshSubclass);
  33815. // Setting properties
  33816. meshSubclass.material = source.material;
  33817. meshSubclass.checkCollisions = source.checkCollisions;
  33818. // Cleaning
  33819. if (disposeSource) {
  33820. for (index = 0; index < meshes.length; index++) {
  33821. if (meshes[index]) {
  33822. meshes[index].dispose();
  33823. }
  33824. }
  33825. }
  33826. // Subdivide
  33827. if (subdivideWithSubMeshes) {
  33828. //-- removal of global submesh
  33829. meshSubclass.releaseSubMeshes();
  33830. index = 0;
  33831. var offset = 0;
  33832. //-- apply subdivision according to index table
  33833. while (index < indiceArray.length) {
  33834. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33835. offset += indiceArray[index];
  33836. index++;
  33837. }
  33838. }
  33839. return meshSubclass;
  33840. };
  33841. // Consts
  33842. Mesh._FRONTSIDE = 0;
  33843. Mesh._BACKSIDE = 1;
  33844. Mesh._DOUBLESIDE = 2;
  33845. Mesh._DEFAULTSIDE = 0;
  33846. Mesh._NO_CAP = 0;
  33847. Mesh._CAP_START = 1;
  33848. Mesh._CAP_END = 2;
  33849. Mesh._CAP_ALL = 3;
  33850. return Mesh;
  33851. }(BABYLON.AbstractMesh));
  33852. BABYLON.Mesh = Mesh;
  33853. })(BABYLON || (BABYLON = {}));
  33854. //# sourceMappingURL=babylon.mesh.js.map
  33855. var BABYLON;
  33856. (function (BABYLON) {
  33857. var BaseSubMesh = /** @class */ (function () {
  33858. function BaseSubMesh() {
  33859. }
  33860. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33861. get: function () {
  33862. return this._materialEffect;
  33863. },
  33864. enumerable: true,
  33865. configurable: true
  33866. });
  33867. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33868. if (defines === void 0) { defines = null; }
  33869. if (this._materialEffect === effect) {
  33870. if (!effect) {
  33871. this._materialDefines = null;
  33872. }
  33873. return;
  33874. }
  33875. this._materialDefines = defines;
  33876. this._materialEffect = effect;
  33877. };
  33878. return BaseSubMesh;
  33879. }());
  33880. BABYLON.BaseSubMesh = BaseSubMesh;
  33881. var SubMesh = /** @class */ (function (_super) {
  33882. __extends(SubMesh, _super);
  33883. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33884. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33885. var _this = _super.call(this) || this;
  33886. _this.materialIndex = materialIndex;
  33887. _this.verticesStart = verticesStart;
  33888. _this.verticesCount = verticesCount;
  33889. _this.indexStart = indexStart;
  33890. _this.indexCount = indexCount;
  33891. _this._renderId = 0;
  33892. _this._mesh = mesh;
  33893. _this._renderingMesh = renderingMesh || mesh;
  33894. mesh.subMeshes.push(_this);
  33895. _this._trianglePlanes = [];
  33896. _this._id = mesh.subMeshes.length - 1;
  33897. if (createBoundingBox) {
  33898. _this.refreshBoundingInfo();
  33899. mesh.computeWorldMatrix(true);
  33900. }
  33901. return _this;
  33902. }
  33903. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33904. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33905. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33906. };
  33907. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33908. get: function () {
  33909. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33910. },
  33911. enumerable: true,
  33912. configurable: true
  33913. });
  33914. /**
  33915. * Returns the submesh BoudingInfo object.
  33916. */
  33917. SubMesh.prototype.getBoundingInfo = function () {
  33918. if (this.IsGlobal) {
  33919. return this._mesh.getBoundingInfo();
  33920. }
  33921. return this._boundingInfo;
  33922. };
  33923. /**
  33924. * Sets the submesh BoundingInfo.
  33925. * Return the SubMesh.
  33926. */
  33927. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33928. this._boundingInfo = boundingInfo;
  33929. return this;
  33930. };
  33931. /**
  33932. * Returns the mesh of the current submesh.
  33933. */
  33934. SubMesh.prototype.getMesh = function () {
  33935. return this._mesh;
  33936. };
  33937. /**
  33938. * Returns the rendering mesh of the submesh.
  33939. */
  33940. SubMesh.prototype.getRenderingMesh = function () {
  33941. return this._renderingMesh;
  33942. };
  33943. /**
  33944. * Returns the submesh material.
  33945. */
  33946. SubMesh.prototype.getMaterial = function () {
  33947. var rootMaterial = this._renderingMesh.material;
  33948. if (rootMaterial === null || rootMaterial === undefined) {
  33949. return this._mesh.getScene().defaultMaterial;
  33950. }
  33951. else if (rootMaterial.getSubMaterial) {
  33952. var multiMaterial = rootMaterial;
  33953. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33954. if (this._currentMaterial !== effectiveMaterial) {
  33955. this._currentMaterial = effectiveMaterial;
  33956. this._materialDefines = null;
  33957. }
  33958. return effectiveMaterial;
  33959. }
  33960. return rootMaterial;
  33961. };
  33962. // Methods
  33963. /**
  33964. * Sets a new updated BoundingInfo object to the submesh.
  33965. * Returns the SubMesh.
  33966. */
  33967. SubMesh.prototype.refreshBoundingInfo = function () {
  33968. this._lastColliderWorldVertices = null;
  33969. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33970. return this;
  33971. }
  33972. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33973. if (!data) {
  33974. this._boundingInfo = this._mesh.getBoundingInfo();
  33975. return this;
  33976. }
  33977. var indices = this._renderingMesh.getIndices();
  33978. var extend;
  33979. //is this the only submesh?
  33980. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33981. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33982. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33983. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33984. }
  33985. else {
  33986. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33987. }
  33988. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33989. return this;
  33990. };
  33991. SubMesh.prototype._checkCollision = function (collider) {
  33992. var boundingInfo = this.getBoundingInfo();
  33993. return boundingInfo._checkCollision(collider);
  33994. };
  33995. /**
  33996. * Updates the submesh BoundingInfo.
  33997. * Returns the Submesh.
  33998. */
  33999. SubMesh.prototype.updateBoundingInfo = function (world) {
  34000. var boundingInfo = this.getBoundingInfo();
  34001. if (!boundingInfo) {
  34002. this.refreshBoundingInfo();
  34003. boundingInfo = this.getBoundingInfo();
  34004. }
  34005. boundingInfo.update(world);
  34006. return this;
  34007. };
  34008. /**
  34009. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34010. * Boolean returned.
  34011. */
  34012. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34013. var boundingInfo = this.getBoundingInfo();
  34014. if (!boundingInfo) {
  34015. return false;
  34016. }
  34017. return boundingInfo.isInFrustum(frustumPlanes);
  34018. };
  34019. /**
  34020. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34021. * Boolean returned.
  34022. */
  34023. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34024. var boundingInfo = this.getBoundingInfo();
  34025. if (!boundingInfo) {
  34026. return false;
  34027. }
  34028. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34029. };
  34030. /**
  34031. * Renders the submesh.
  34032. * Returns it.
  34033. */
  34034. SubMesh.prototype.render = function (enableAlphaMode) {
  34035. this._renderingMesh.render(this, enableAlphaMode);
  34036. return this;
  34037. };
  34038. /**
  34039. * Returns a new Index Buffer.
  34040. * Type returned : WebGLBuffer.
  34041. */
  34042. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34043. if (!this._linesIndexBuffer) {
  34044. var linesIndices = [];
  34045. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34046. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34047. }
  34048. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34049. this.linesIndexCount = linesIndices.length;
  34050. }
  34051. return this._linesIndexBuffer;
  34052. };
  34053. /**
  34054. * True is the passed Ray intersects the submesh bounding box.
  34055. * Boolean returned.
  34056. */
  34057. SubMesh.prototype.canIntersects = function (ray) {
  34058. var boundingInfo = this.getBoundingInfo();
  34059. if (!boundingInfo) {
  34060. return false;
  34061. }
  34062. return ray.intersectsBox(boundingInfo.boundingBox);
  34063. };
  34064. /**
  34065. * Returns an object IntersectionInfo.
  34066. */
  34067. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34068. var intersectInfo = null;
  34069. var material = this.getMaterial();
  34070. if (!material) {
  34071. return null;
  34072. }
  34073. switch (material.fillMode) {
  34074. case BABYLON.Material.PointListDrawMode:
  34075. case BABYLON.Material.LineListDrawMode:
  34076. case BABYLON.Material.LineLoopDrawMode:
  34077. case BABYLON.Material.LineStripDrawMode:
  34078. case BABYLON.Material.TriangleFanDrawMode:
  34079. case BABYLON.Material.TriangleStripDrawMode:
  34080. return null;
  34081. }
  34082. // LineMesh first as it's also a Mesh...
  34083. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34084. var lineMesh = this._mesh;
  34085. // Line test
  34086. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34087. var p0 = positions[indices[index]];
  34088. var p1 = positions[indices[index + 1]];
  34089. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34090. if (length < 0) {
  34091. continue;
  34092. }
  34093. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34094. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34095. if (fastCheck) {
  34096. break;
  34097. }
  34098. }
  34099. }
  34100. }
  34101. else {
  34102. // Triangles test
  34103. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34104. var p0 = positions[indices[index]];
  34105. var p1 = positions[indices[index + 1]];
  34106. var p2 = positions[indices[index + 2]];
  34107. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34108. if (currentIntersectInfo) {
  34109. if (currentIntersectInfo.distance < 0) {
  34110. continue;
  34111. }
  34112. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34113. intersectInfo = currentIntersectInfo;
  34114. intersectInfo.faceId = index / 3;
  34115. if (fastCheck) {
  34116. break;
  34117. }
  34118. }
  34119. }
  34120. }
  34121. }
  34122. return intersectInfo;
  34123. };
  34124. SubMesh.prototype._rebuild = function () {
  34125. if (this._linesIndexBuffer) {
  34126. this._linesIndexBuffer = null;
  34127. }
  34128. };
  34129. // Clone
  34130. /**
  34131. * Creates a new Submesh from the passed Mesh.
  34132. */
  34133. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34134. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34135. if (!this.IsGlobal) {
  34136. var boundingInfo = this.getBoundingInfo();
  34137. if (!boundingInfo) {
  34138. return result;
  34139. }
  34140. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34141. }
  34142. return result;
  34143. };
  34144. // Dispose
  34145. /**
  34146. * Disposes the Submesh.
  34147. * Returns nothing.
  34148. */
  34149. SubMesh.prototype.dispose = function () {
  34150. if (this._linesIndexBuffer) {
  34151. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34152. this._linesIndexBuffer = null;
  34153. }
  34154. // Remove from mesh
  34155. var index = this._mesh.subMeshes.indexOf(this);
  34156. this._mesh.subMeshes.splice(index, 1);
  34157. };
  34158. // Statics
  34159. /**
  34160. * Creates a new Submesh from the passed parameters :
  34161. * - materialIndex (integer) : the index of the main mesh material.
  34162. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34163. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34164. * - mesh (Mesh) : the main mesh to create the submesh from.
  34165. * - renderingMesh (optional Mesh) : rendering mesh.
  34166. */
  34167. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34168. var minVertexIndex = Number.MAX_VALUE;
  34169. var maxVertexIndex = -Number.MAX_VALUE;
  34170. renderingMesh = (renderingMesh || mesh);
  34171. var indices = renderingMesh.getIndices();
  34172. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34173. var vertexIndex = indices[index];
  34174. if (vertexIndex < minVertexIndex)
  34175. minVertexIndex = vertexIndex;
  34176. if (vertexIndex > maxVertexIndex)
  34177. maxVertexIndex = vertexIndex;
  34178. }
  34179. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34180. };
  34181. return SubMesh;
  34182. }(BaseSubMesh));
  34183. BABYLON.SubMesh = SubMesh;
  34184. })(BABYLON || (BABYLON = {}));
  34185. //# sourceMappingURL=babylon.subMesh.js.map
  34186. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34187. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34188. s = arguments[i];
  34189. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34190. t[p] = s[p];
  34191. }
  34192. return t;
  34193. };
  34194. var BABYLON;
  34195. (function (BABYLON) {
  34196. /**
  34197. * Manages the defines for the Material
  34198. */
  34199. var MaterialDefines = /** @class */ (function () {
  34200. function MaterialDefines() {
  34201. this._isDirty = true;
  34202. /** @hidden */
  34203. this._areLightsDirty = true;
  34204. /** @hidden */
  34205. this._areAttributesDirty = true;
  34206. /** @hidden */
  34207. this._areTexturesDirty = true;
  34208. /** @hidden */
  34209. this._areFresnelDirty = true;
  34210. /** @hidden */
  34211. this._areMiscDirty = true;
  34212. /** @hidden */
  34213. this._areImageProcessingDirty = true;
  34214. /** @hidden */
  34215. this._normals = false;
  34216. /** @hidden */
  34217. this._uvs = false;
  34218. /** @hidden */
  34219. this._needNormals = false;
  34220. /** @hidden */
  34221. this._needUVs = false;
  34222. }
  34223. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34224. /**
  34225. * Specifies if the material needs to be re-calculated
  34226. */
  34227. get: function () {
  34228. return this._isDirty;
  34229. },
  34230. enumerable: true,
  34231. configurable: true
  34232. });
  34233. /**
  34234. * Marks the material to indicate that it has been re-calculated
  34235. */
  34236. MaterialDefines.prototype.markAsProcessed = function () {
  34237. this._isDirty = false;
  34238. this._areAttributesDirty = false;
  34239. this._areTexturesDirty = false;
  34240. this._areFresnelDirty = false;
  34241. this._areLightsDirty = false;
  34242. this._areMiscDirty = false;
  34243. this._areImageProcessingDirty = false;
  34244. };
  34245. /**
  34246. * Marks the material to indicate that it needs to be re-calculated
  34247. */
  34248. MaterialDefines.prototype.markAsUnprocessed = function () {
  34249. this._isDirty = true;
  34250. };
  34251. /**
  34252. * Marks the material to indicate all of its defines need to be re-calculated
  34253. */
  34254. MaterialDefines.prototype.markAllAsDirty = function () {
  34255. this._areTexturesDirty = true;
  34256. this._areAttributesDirty = true;
  34257. this._areLightsDirty = true;
  34258. this._areFresnelDirty = true;
  34259. this._areMiscDirty = true;
  34260. this._areImageProcessingDirty = true;
  34261. this._isDirty = true;
  34262. };
  34263. /**
  34264. * Marks the material to indicate that image processing needs to be re-calculated
  34265. */
  34266. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34267. this._areImageProcessingDirty = true;
  34268. this._isDirty = true;
  34269. };
  34270. /**
  34271. * Marks the material to indicate the lights need to be re-calculated
  34272. */
  34273. MaterialDefines.prototype.markAsLightDirty = function () {
  34274. this._areLightsDirty = true;
  34275. this._isDirty = true;
  34276. };
  34277. /**
  34278. * Marks the attribute state as changed
  34279. */
  34280. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34281. this._areAttributesDirty = true;
  34282. this._isDirty = true;
  34283. };
  34284. /**
  34285. * Marks the texture state as changed
  34286. */
  34287. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34288. this._areTexturesDirty = true;
  34289. this._isDirty = true;
  34290. };
  34291. /**
  34292. * Marks the fresnel state as changed
  34293. */
  34294. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34295. this._areFresnelDirty = true;
  34296. this._isDirty = true;
  34297. };
  34298. /**
  34299. * Marks the misc state as changed
  34300. */
  34301. MaterialDefines.prototype.markAsMiscDirty = function () {
  34302. this._areMiscDirty = true;
  34303. this._isDirty = true;
  34304. };
  34305. /**
  34306. * Rebuilds the material defines
  34307. */
  34308. MaterialDefines.prototype.rebuild = function () {
  34309. if (this._keys) {
  34310. delete this._keys;
  34311. }
  34312. this._keys = [];
  34313. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34314. var key = _a[_i];
  34315. if (key[0] === "_") {
  34316. continue;
  34317. }
  34318. this._keys.push(key);
  34319. }
  34320. };
  34321. /**
  34322. * Specifies if two material defines are equal
  34323. * @param other - A material define instance to compare to
  34324. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34325. */
  34326. MaterialDefines.prototype.isEqual = function (other) {
  34327. if (this._keys.length !== other._keys.length) {
  34328. return false;
  34329. }
  34330. for (var index = 0; index < this._keys.length; index++) {
  34331. var prop = this._keys[index];
  34332. if (this[prop] !== other[prop]) {
  34333. return false;
  34334. }
  34335. }
  34336. return true;
  34337. };
  34338. /**
  34339. * Clones this instance's defines to another instance
  34340. * @param other - material defines to clone values to
  34341. */
  34342. MaterialDefines.prototype.cloneTo = function (other) {
  34343. if (this._keys.length !== other._keys.length) {
  34344. other._keys = this._keys.slice(0);
  34345. }
  34346. for (var index = 0; index < this._keys.length; index++) {
  34347. var prop = this._keys[index];
  34348. other[prop] = this[prop];
  34349. }
  34350. };
  34351. /**
  34352. * Resets the material define values
  34353. */
  34354. MaterialDefines.prototype.reset = function () {
  34355. for (var index = 0; index < this._keys.length; index++) {
  34356. var prop = this._keys[index];
  34357. var type = typeof this[prop];
  34358. switch (type) {
  34359. case "number":
  34360. this[prop] = 0;
  34361. break;
  34362. case "string":
  34363. this[prop] = "";
  34364. break;
  34365. default:
  34366. this[prop] = false;
  34367. break;
  34368. }
  34369. }
  34370. };
  34371. /**
  34372. * Converts the material define values to a string
  34373. * @returns - String of material define information
  34374. */
  34375. MaterialDefines.prototype.toString = function () {
  34376. var result = "";
  34377. for (var index = 0; index < this._keys.length; index++) {
  34378. var prop = this._keys[index];
  34379. var value = this[prop];
  34380. var type = typeof value;
  34381. switch (type) {
  34382. case "number":
  34383. case "string":
  34384. result += "#define " + prop + " " + value + "\n";
  34385. break;
  34386. default:
  34387. if (value) {
  34388. result += "#define " + prop + "\n";
  34389. }
  34390. break;
  34391. }
  34392. }
  34393. return result;
  34394. };
  34395. return MaterialDefines;
  34396. }());
  34397. BABYLON.MaterialDefines = MaterialDefines;
  34398. /**
  34399. * Base class for the main features of a material in Babylon.js
  34400. */
  34401. var Material = /** @class */ (function () {
  34402. /**
  34403. * Creates a material instance
  34404. * @param name defines the name of the material
  34405. * @param scene defines the scene to reference
  34406. * @param doNotAdd specifies if the material should be added to the scene
  34407. */
  34408. function Material(name, scene, doNotAdd) {
  34409. /**
  34410. * Specifies if the ready state should be checked on each call
  34411. */
  34412. this.checkReadyOnEveryCall = false;
  34413. /**
  34414. * Specifies if the ready state should be checked once
  34415. */
  34416. this.checkReadyOnlyOnce = false;
  34417. /**
  34418. * The state of the material
  34419. */
  34420. this.state = "";
  34421. /**
  34422. * The alpha value of the material
  34423. */
  34424. this._alpha = 1.0;
  34425. /**
  34426. * Specifies if back face culling is enabled
  34427. */
  34428. this._backFaceCulling = true;
  34429. /**
  34430. * Specifies if the material should be serialized
  34431. */
  34432. this.doNotSerialize = false;
  34433. /**
  34434. * Specifies if the effect should be stored on sub meshes
  34435. */
  34436. this.storeEffectOnSubMeshes = false;
  34437. /**
  34438. * An event triggered when the material is disposed
  34439. */
  34440. this.onDisposeObservable = new BABYLON.Observable();
  34441. /**
  34442. * An event triggered when the material is bound
  34443. */
  34444. this.onBindObservable = new BABYLON.Observable();
  34445. /**
  34446. * An event triggered when the material is unbound
  34447. */
  34448. this.onUnBindObservable = new BABYLON.Observable();
  34449. /**
  34450. * Stores the value of the alpha mode
  34451. */
  34452. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34453. /**
  34454. * Stores the state of the need depth pre-pass value
  34455. */
  34456. this._needDepthPrePass = false;
  34457. /**
  34458. * Specifies if depth writing should be disabled
  34459. */
  34460. this.disableDepthWrite = false;
  34461. /**
  34462. * Specifies if depth writing should be forced
  34463. */
  34464. this.forceDepthWrite = false;
  34465. /**
  34466. * Specifies if there should be a separate pass for culling
  34467. */
  34468. this.separateCullingPass = false;
  34469. /**
  34470. * Stores the state specifing if fog should be enabled
  34471. */
  34472. this._fogEnabled = true;
  34473. /**
  34474. * Stores the size of points
  34475. */
  34476. this.pointSize = 1.0;
  34477. /**
  34478. * Stores the z offset value
  34479. */
  34480. this.zOffset = 0;
  34481. /**
  34482. * Specifies if the material was previously ready
  34483. */
  34484. this._wasPreviouslyReady = false;
  34485. /**
  34486. * Stores the fill mode state
  34487. */
  34488. this._fillMode = Material.TriangleFillMode;
  34489. this.name = name;
  34490. this.id = name || BABYLON.Tools.RandomId();
  34491. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34492. this.uniqueId = this._scene.getUniqueId();
  34493. if (this._scene.useRightHandedSystem) {
  34494. this.sideOrientation = Material.ClockWiseSideOrientation;
  34495. }
  34496. else {
  34497. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34498. }
  34499. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34500. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34501. if (!doNotAdd) {
  34502. this._scene.materials.push(this);
  34503. }
  34504. }
  34505. Object.defineProperty(Material, "TriangleFillMode", {
  34506. /**
  34507. * Returns the triangle fill mode
  34508. */
  34509. get: function () {
  34510. return Material._TriangleFillMode;
  34511. },
  34512. enumerable: true,
  34513. configurable: true
  34514. });
  34515. Object.defineProperty(Material, "WireFrameFillMode", {
  34516. /**
  34517. * Returns the wireframe mode
  34518. */
  34519. get: function () {
  34520. return Material._WireFrameFillMode;
  34521. },
  34522. enumerable: true,
  34523. configurable: true
  34524. });
  34525. Object.defineProperty(Material, "PointFillMode", {
  34526. /**
  34527. * Returns the point fill mode
  34528. */
  34529. get: function () {
  34530. return Material._PointFillMode;
  34531. },
  34532. enumerable: true,
  34533. configurable: true
  34534. });
  34535. Object.defineProperty(Material, "PointListDrawMode", {
  34536. /**
  34537. * Returns the point list draw mode
  34538. */
  34539. get: function () {
  34540. return Material._PointListDrawMode;
  34541. },
  34542. enumerable: true,
  34543. configurable: true
  34544. });
  34545. Object.defineProperty(Material, "LineListDrawMode", {
  34546. /**
  34547. * Returns the line list draw mode
  34548. */
  34549. get: function () {
  34550. return Material._LineListDrawMode;
  34551. },
  34552. enumerable: true,
  34553. configurable: true
  34554. });
  34555. Object.defineProperty(Material, "LineLoopDrawMode", {
  34556. /**
  34557. * Returns the line loop draw mode
  34558. */
  34559. get: function () {
  34560. return Material._LineLoopDrawMode;
  34561. },
  34562. enumerable: true,
  34563. configurable: true
  34564. });
  34565. Object.defineProperty(Material, "LineStripDrawMode", {
  34566. /**
  34567. * Returns the line strip draw mode
  34568. */
  34569. get: function () {
  34570. return Material._LineStripDrawMode;
  34571. },
  34572. enumerable: true,
  34573. configurable: true
  34574. });
  34575. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34576. /**
  34577. * Returns the triangle strip draw mode
  34578. */
  34579. get: function () {
  34580. return Material._TriangleStripDrawMode;
  34581. },
  34582. enumerable: true,
  34583. configurable: true
  34584. });
  34585. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34586. /**
  34587. * Returns the triangle fan draw mode
  34588. */
  34589. get: function () {
  34590. return Material._TriangleFanDrawMode;
  34591. },
  34592. enumerable: true,
  34593. configurable: true
  34594. });
  34595. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34596. /**
  34597. * Returns the clock-wise side orientation
  34598. */
  34599. get: function () {
  34600. return Material._ClockWiseSideOrientation;
  34601. },
  34602. enumerable: true,
  34603. configurable: true
  34604. });
  34605. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34606. /**
  34607. * Returns the counter clock-wise side orientation
  34608. */
  34609. get: function () {
  34610. return Material._CounterClockWiseSideOrientation;
  34611. },
  34612. enumerable: true,
  34613. configurable: true
  34614. });
  34615. Object.defineProperty(Material, "TextureDirtyFlag", {
  34616. /**
  34617. * Returns the dirty texture flag value
  34618. */
  34619. get: function () {
  34620. return Material._TextureDirtyFlag;
  34621. },
  34622. enumerable: true,
  34623. configurable: true
  34624. });
  34625. Object.defineProperty(Material, "LightDirtyFlag", {
  34626. /**
  34627. * Returns the dirty light flag value
  34628. */
  34629. get: function () {
  34630. return Material._LightDirtyFlag;
  34631. },
  34632. enumerable: true,
  34633. configurable: true
  34634. });
  34635. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34636. /**
  34637. * Returns the dirty fresnel flag value
  34638. */
  34639. get: function () {
  34640. return Material._FresnelDirtyFlag;
  34641. },
  34642. enumerable: true,
  34643. configurable: true
  34644. });
  34645. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34646. /**
  34647. * Returns the dirty attributes flag value
  34648. */
  34649. get: function () {
  34650. return Material._AttributesDirtyFlag;
  34651. },
  34652. enumerable: true,
  34653. configurable: true
  34654. });
  34655. Object.defineProperty(Material, "MiscDirtyFlag", {
  34656. /**
  34657. * Returns the dirty misc flag value
  34658. */
  34659. get: function () {
  34660. return Material._MiscDirtyFlag;
  34661. },
  34662. enumerable: true,
  34663. configurable: true
  34664. });
  34665. Object.defineProperty(Material.prototype, "alpha", {
  34666. /**
  34667. * Gets the alpha value of the material
  34668. */
  34669. get: function () {
  34670. return this._alpha;
  34671. },
  34672. /**
  34673. * Sets the alpha value of the material
  34674. */
  34675. set: function (value) {
  34676. if (this._alpha === value) {
  34677. return;
  34678. }
  34679. this._alpha = value;
  34680. this.markAsDirty(Material.MiscDirtyFlag);
  34681. },
  34682. enumerable: true,
  34683. configurable: true
  34684. });
  34685. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34686. /**
  34687. * Gets the back-face culling state
  34688. */
  34689. get: function () {
  34690. return this._backFaceCulling;
  34691. },
  34692. /**
  34693. * Sets the back-face culling state
  34694. */
  34695. set: function (value) {
  34696. if (this._backFaceCulling === value) {
  34697. return;
  34698. }
  34699. this._backFaceCulling = value;
  34700. this.markAsDirty(Material.TextureDirtyFlag);
  34701. },
  34702. enumerable: true,
  34703. configurable: true
  34704. });
  34705. Object.defineProperty(Material.prototype, "onDispose", {
  34706. /**
  34707. * Called during a dispose event
  34708. */
  34709. set: function (callback) {
  34710. if (this._onDisposeObserver) {
  34711. this.onDisposeObservable.remove(this._onDisposeObserver);
  34712. }
  34713. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34714. },
  34715. enumerable: true,
  34716. configurable: true
  34717. });
  34718. Object.defineProperty(Material.prototype, "onBind", {
  34719. /**
  34720. * Called during a bind event
  34721. */
  34722. set: function (callback) {
  34723. if (this._onBindObserver) {
  34724. this.onBindObservable.remove(this._onBindObserver);
  34725. }
  34726. this._onBindObserver = this.onBindObservable.add(callback);
  34727. },
  34728. enumerable: true,
  34729. configurable: true
  34730. });
  34731. Object.defineProperty(Material.prototype, "alphaMode", {
  34732. /**
  34733. * Gets the value of the alpha mode
  34734. */
  34735. get: function () {
  34736. return this._alphaMode;
  34737. },
  34738. /**
  34739. * Sets the value of the alpha mode.
  34740. *
  34741. * | Value | Type | Description |
  34742. * | --- | --- | --- |
  34743. * | 0 | ALPHA_DISABLE | |
  34744. * | 1 | ALPHA_ADD | |
  34745. * | 2 | ALPHA_COMBINE | |
  34746. * | 3 | ALPHA_SUBTRACT | |
  34747. * | 4 | ALPHA_MULTIPLY | |
  34748. * | 5 | ALPHA_MAXIMIZED | |
  34749. * | 6 | ALPHA_ONEONE | |
  34750. * | 7 | ALPHA_PREMULTIPLIED | |
  34751. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34752. * | 9 | ALPHA_INTERPOLATE | |
  34753. * | 10 | ALPHA_SCREENMODE | |
  34754. *
  34755. */
  34756. set: function (value) {
  34757. if (this._alphaMode === value) {
  34758. return;
  34759. }
  34760. this._alphaMode = value;
  34761. this.markAsDirty(Material.TextureDirtyFlag);
  34762. },
  34763. enumerable: true,
  34764. configurable: true
  34765. });
  34766. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34767. /**
  34768. * Gets the depth pre-pass value
  34769. */
  34770. get: function () {
  34771. return this._needDepthPrePass;
  34772. },
  34773. /**
  34774. * Sets the need depth pre-pass value
  34775. */
  34776. set: function (value) {
  34777. if (this._needDepthPrePass === value) {
  34778. return;
  34779. }
  34780. this._needDepthPrePass = value;
  34781. if (this._needDepthPrePass) {
  34782. this.checkReadyOnEveryCall = true;
  34783. }
  34784. },
  34785. enumerable: true,
  34786. configurable: true
  34787. });
  34788. Object.defineProperty(Material.prototype, "fogEnabled", {
  34789. /**
  34790. * Gets the value of the fog enabled state
  34791. */
  34792. get: function () {
  34793. return this._fogEnabled;
  34794. },
  34795. /**
  34796. * Sets the state for enabling fog
  34797. */
  34798. set: function (value) {
  34799. if (this._fogEnabled === value) {
  34800. return;
  34801. }
  34802. this._fogEnabled = value;
  34803. this.markAsDirty(Material.MiscDirtyFlag);
  34804. },
  34805. enumerable: true,
  34806. configurable: true
  34807. });
  34808. Object.defineProperty(Material.prototype, "wireframe", {
  34809. /**
  34810. * Gets a value specifying if wireframe mode is enabled
  34811. */
  34812. get: function () {
  34813. switch (this._fillMode) {
  34814. case Material.WireFrameFillMode:
  34815. case Material.LineListDrawMode:
  34816. case Material.LineLoopDrawMode:
  34817. case Material.LineStripDrawMode:
  34818. return true;
  34819. }
  34820. return this._scene.forceWireframe;
  34821. },
  34822. /**
  34823. * Sets the state of wireframe mode
  34824. */
  34825. set: function (value) {
  34826. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34827. },
  34828. enumerable: true,
  34829. configurable: true
  34830. });
  34831. Object.defineProperty(Material.prototype, "pointsCloud", {
  34832. /**
  34833. * Gets the value specifying if point clouds are enabled
  34834. */
  34835. get: function () {
  34836. switch (this._fillMode) {
  34837. case Material.PointFillMode:
  34838. case Material.PointListDrawMode:
  34839. return true;
  34840. }
  34841. return this._scene.forcePointsCloud;
  34842. },
  34843. /**
  34844. * Sets the state of point cloud mode
  34845. */
  34846. set: function (value) {
  34847. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34848. },
  34849. enumerable: true,
  34850. configurable: true
  34851. });
  34852. Object.defineProperty(Material.prototype, "fillMode", {
  34853. /**
  34854. * Gets the material fill mode
  34855. */
  34856. get: function () {
  34857. return this._fillMode;
  34858. },
  34859. /**
  34860. * Sets the material fill mode
  34861. */
  34862. set: function (value) {
  34863. if (this._fillMode === value) {
  34864. return;
  34865. }
  34866. this._fillMode = value;
  34867. this.markAsDirty(Material.MiscDirtyFlag);
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. /**
  34873. * Returns a string representation of the current material
  34874. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34875. * @returns a string with material information
  34876. */
  34877. Material.prototype.toString = function (fullDetails) {
  34878. var ret = "Name: " + this.name;
  34879. if (fullDetails) {
  34880. }
  34881. return ret;
  34882. };
  34883. /**
  34884. * Gets the class name of the material
  34885. * @returns a string with the class name of the material
  34886. */
  34887. Material.prototype.getClassName = function () {
  34888. return "Material";
  34889. };
  34890. Object.defineProperty(Material.prototype, "isFrozen", {
  34891. /**
  34892. * Specifies if updates for the material been locked
  34893. */
  34894. get: function () {
  34895. return this.checkReadyOnlyOnce;
  34896. },
  34897. enumerable: true,
  34898. configurable: true
  34899. });
  34900. /**
  34901. * Locks updates for the material
  34902. */
  34903. Material.prototype.freeze = function () {
  34904. this.checkReadyOnlyOnce = true;
  34905. };
  34906. /**
  34907. * Unlocks updates for the material
  34908. */
  34909. Material.prototype.unfreeze = function () {
  34910. this.checkReadyOnlyOnce = false;
  34911. };
  34912. /**
  34913. * Specifies if the material is ready to be used
  34914. * @param mesh defines the mesh to check
  34915. * @param useInstances specifies if instances should be used
  34916. * @returns a boolean indicating if the material is ready to be used
  34917. */
  34918. Material.prototype.isReady = function (mesh, useInstances) {
  34919. return true;
  34920. };
  34921. /**
  34922. * Specifies that the submesh is ready to be used
  34923. * @param mesh defines the mesh to check
  34924. * @param subMesh defines which submesh to check
  34925. * @param useInstances specifies that instances should be used
  34926. * @returns a boolean indicating that the submesh is ready or not
  34927. */
  34928. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34929. return false;
  34930. };
  34931. /**
  34932. * Returns the material effect
  34933. * @returns the effect associated with the material
  34934. */
  34935. Material.prototype.getEffect = function () {
  34936. return this._effect;
  34937. };
  34938. /**
  34939. * Returns the current scene
  34940. * @returns a Scene
  34941. */
  34942. Material.prototype.getScene = function () {
  34943. return this._scene;
  34944. };
  34945. /**
  34946. * Specifies if the material will require alpha blending
  34947. * @returns a boolean specifying if alpha blending is needed
  34948. */
  34949. Material.prototype.needAlphaBlending = function () {
  34950. return (this.alpha < 1.0);
  34951. };
  34952. /**
  34953. * Specifies if the mesh will require alpha blending
  34954. * @param mesh defines the mesh to check
  34955. * @returns a boolean specifying if alpha blending is needed for the mesh
  34956. */
  34957. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34958. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34959. };
  34960. /**
  34961. * Specifies if this material should be rendered in alpha test mode
  34962. * @returns a boolean specifying if an alpha test is needed.
  34963. */
  34964. Material.prototype.needAlphaTesting = function () {
  34965. return false;
  34966. };
  34967. /**
  34968. * Gets the texture used for the alpha test
  34969. * @returns the texture to use for alpha testing
  34970. */
  34971. Material.prototype.getAlphaTestTexture = function () {
  34972. return null;
  34973. };
  34974. /**
  34975. * Marks the material to indicate that it needs to be re-calculated
  34976. */
  34977. Material.prototype.markDirty = function () {
  34978. this._wasPreviouslyReady = false;
  34979. };
  34980. /** @hidden */
  34981. Material.prototype._preBind = function (effect, overrideOrientation) {
  34982. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34983. var engine = this._scene.getEngine();
  34984. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34985. var reverse = orientation === Material.ClockWiseSideOrientation;
  34986. engine.enableEffect(effect ? effect : this._effect);
  34987. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34988. return reverse;
  34989. };
  34990. /**
  34991. * Binds the material to the mesh
  34992. * @param world defines the world transformation matrix
  34993. * @param mesh defines the mesh to bind the material to
  34994. */
  34995. Material.prototype.bind = function (world, mesh) {
  34996. };
  34997. /**
  34998. * Binds the submesh to the material
  34999. * @param world defines the world transformation matrix
  35000. * @param mesh defines the mesh containing the submesh
  35001. * @param subMesh defines the submesh to bind the material to
  35002. */
  35003. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35004. };
  35005. /**
  35006. * Binds the world matrix to the material
  35007. * @param world defines the world transformation matrix
  35008. */
  35009. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35010. };
  35011. /**
  35012. * Binds the scene's uniform buffer to the effect.
  35013. * @param effect defines the effect to bind to the scene uniform buffer
  35014. * @param sceneUbo defines the uniform buffer storing scene data
  35015. */
  35016. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35017. sceneUbo.bindToEffect(effect, "Scene");
  35018. };
  35019. /**
  35020. * Binds the view matrix to the effect
  35021. * @param effect defines the effect to bind the view matrix to
  35022. */
  35023. Material.prototype.bindView = function (effect) {
  35024. if (!this._useUBO) {
  35025. effect.setMatrix("view", this.getScene().getViewMatrix());
  35026. }
  35027. else {
  35028. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35029. }
  35030. };
  35031. /**
  35032. * Binds the view projection matrix to the effect
  35033. * @param effect defines the effect to bind the view projection matrix to
  35034. */
  35035. Material.prototype.bindViewProjection = function (effect) {
  35036. if (!this._useUBO) {
  35037. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35038. }
  35039. else {
  35040. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35041. }
  35042. };
  35043. /**
  35044. * Specifies if material alpha testing should be turned on for the mesh
  35045. * @param mesh defines the mesh to check
  35046. */
  35047. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35048. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35049. };
  35050. /**
  35051. * Processes to execute after binding the material to a mesh
  35052. * @param mesh defines the rendered mesh
  35053. */
  35054. Material.prototype._afterBind = function (mesh) {
  35055. this._scene._cachedMaterial = this;
  35056. if (mesh) {
  35057. this._scene._cachedVisibility = mesh.visibility;
  35058. }
  35059. else {
  35060. this._scene._cachedVisibility = 1;
  35061. }
  35062. if (mesh) {
  35063. this.onBindObservable.notifyObservers(mesh);
  35064. }
  35065. if (this.disableDepthWrite) {
  35066. var engine = this._scene.getEngine();
  35067. this._cachedDepthWriteState = engine.getDepthWrite();
  35068. engine.setDepthWrite(false);
  35069. }
  35070. };
  35071. /**
  35072. * Unbinds the material from the mesh
  35073. */
  35074. Material.prototype.unbind = function () {
  35075. this.onUnBindObservable.notifyObservers(this);
  35076. if (this.disableDepthWrite) {
  35077. var engine = this._scene.getEngine();
  35078. engine.setDepthWrite(this._cachedDepthWriteState);
  35079. }
  35080. };
  35081. /**
  35082. * Gets the active textures from the material
  35083. * @returns an array of textures
  35084. */
  35085. Material.prototype.getActiveTextures = function () {
  35086. return [];
  35087. };
  35088. /**
  35089. * Specifies if the material uses a texture
  35090. * @param texture defines the texture to check against the material
  35091. * @returns a boolean specifying if the material uses the texture
  35092. */
  35093. Material.prototype.hasTexture = function (texture) {
  35094. return false;
  35095. };
  35096. /**
  35097. * Makes a duplicate of the material, and gives it a new name
  35098. * @param name defines the new name for the duplicated material
  35099. * @returns the cloned material
  35100. */
  35101. Material.prototype.clone = function (name) {
  35102. return null;
  35103. };
  35104. /**
  35105. * Gets the meshes bound to the material
  35106. * @returns an array of meshes bound to the material
  35107. */
  35108. Material.prototype.getBindedMeshes = function () {
  35109. var result = new Array();
  35110. for (var index = 0; index < this._scene.meshes.length; index++) {
  35111. var mesh = this._scene.meshes[index];
  35112. if (mesh.material === this) {
  35113. result.push(mesh);
  35114. }
  35115. }
  35116. return result;
  35117. };
  35118. /**
  35119. * Force shader compilation
  35120. * @param mesh defines the mesh associated with this material
  35121. * @param onCompiled defines a function to execute once the material is compiled
  35122. * @param options defines the options to configure the compilation
  35123. */
  35124. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35125. var _this = this;
  35126. var localOptions = __assign({ clipPlane: false }, options);
  35127. var subMesh = new BABYLON.BaseSubMesh();
  35128. var scene = this.getScene();
  35129. var checkReady = function () {
  35130. if (!_this._scene || !_this._scene.getEngine()) {
  35131. return;
  35132. }
  35133. if (subMesh._materialDefines) {
  35134. subMesh._materialDefines._renderId = -1;
  35135. }
  35136. var clipPlaneState = scene.clipPlane;
  35137. if (localOptions.clipPlane) {
  35138. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35139. }
  35140. if (_this.storeEffectOnSubMeshes) {
  35141. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35142. if (onCompiled) {
  35143. onCompiled(_this);
  35144. }
  35145. }
  35146. else {
  35147. setTimeout(checkReady, 16);
  35148. }
  35149. }
  35150. else {
  35151. if (_this.isReady(mesh)) {
  35152. if (onCompiled) {
  35153. onCompiled(_this);
  35154. }
  35155. }
  35156. else {
  35157. setTimeout(checkReady, 16);
  35158. }
  35159. }
  35160. if (localOptions.clipPlane) {
  35161. scene.clipPlane = clipPlaneState;
  35162. }
  35163. };
  35164. checkReady();
  35165. };
  35166. /**
  35167. * Force shader compilation
  35168. * @param mesh defines the mesh that will use this material
  35169. * @param options defines additional options for compiling the shaders
  35170. * @returns a promise that resolves when the compilation completes
  35171. */
  35172. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35173. var _this = this;
  35174. return new Promise(function (resolve) {
  35175. _this.forceCompilation(mesh, function () {
  35176. resolve();
  35177. }, options);
  35178. });
  35179. };
  35180. /**
  35181. * Marks a define in the material to indicate that it needs to be re-computed
  35182. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35183. */
  35184. Material.prototype.markAsDirty = function (flag) {
  35185. if (flag & Material.TextureDirtyFlag) {
  35186. this._markAllSubMeshesAsTexturesDirty();
  35187. }
  35188. if (flag & Material.LightDirtyFlag) {
  35189. this._markAllSubMeshesAsLightsDirty();
  35190. }
  35191. if (flag & Material.FresnelDirtyFlag) {
  35192. this._markAllSubMeshesAsFresnelDirty();
  35193. }
  35194. if (flag & Material.AttributesDirtyFlag) {
  35195. this._markAllSubMeshesAsAttributesDirty();
  35196. }
  35197. if (flag & Material.MiscDirtyFlag) {
  35198. this._markAllSubMeshesAsMiscDirty();
  35199. }
  35200. this.getScene().resetCachedMaterial();
  35201. };
  35202. /**
  35203. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35204. * @param func defines a function which checks material defines against the submeshes
  35205. */
  35206. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35207. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35208. var mesh = _a[_i];
  35209. if (!mesh.subMeshes) {
  35210. continue;
  35211. }
  35212. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35213. var subMesh = _c[_b];
  35214. if (subMesh.getMaterial() !== this) {
  35215. continue;
  35216. }
  35217. if (!subMesh._materialDefines) {
  35218. continue;
  35219. }
  35220. func(subMesh._materialDefines);
  35221. }
  35222. }
  35223. };
  35224. /**
  35225. * Indicates that image processing needs to be re-calculated for all submeshes
  35226. */
  35227. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35228. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35229. };
  35230. /**
  35231. * Indicates that textures need to be re-calculated for all submeshes
  35232. */
  35233. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35234. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35235. };
  35236. /**
  35237. * Indicates that fresnel needs to be re-calculated for all submeshes
  35238. */
  35239. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35240. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35241. };
  35242. /**
  35243. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35244. */
  35245. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35246. this._markAllSubMeshesAsDirty(function (defines) {
  35247. defines.markAsFresnelDirty();
  35248. defines.markAsMiscDirty();
  35249. });
  35250. };
  35251. /**
  35252. * Indicates that lights need to be re-calculated for all submeshes
  35253. */
  35254. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35255. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35256. };
  35257. /**
  35258. * Indicates that attributes need to be re-calculated for all submeshes
  35259. */
  35260. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35261. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35262. };
  35263. /**
  35264. * Indicates that misc needs to be re-calculated for all submeshes
  35265. */
  35266. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35267. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35268. };
  35269. /**
  35270. * Indicates that textures and misc need to be re-calculated for all submeshes
  35271. */
  35272. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35273. this._markAllSubMeshesAsDirty(function (defines) {
  35274. defines.markAsTexturesDirty();
  35275. defines.markAsMiscDirty();
  35276. });
  35277. };
  35278. /**
  35279. * Disposes the material
  35280. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35281. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35282. */
  35283. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35284. // Animations
  35285. this.getScene().stopAnimation(this);
  35286. this.getScene().freeProcessedMaterials();
  35287. // Remove from scene
  35288. var index = this._scene.materials.indexOf(this);
  35289. if (index >= 0) {
  35290. this._scene.materials.splice(index, 1);
  35291. }
  35292. // Remove from meshes
  35293. for (index = 0; index < this._scene.meshes.length; index++) {
  35294. var mesh = this._scene.meshes[index];
  35295. if (mesh.material === this) {
  35296. mesh.material = null;
  35297. if (mesh.geometry) {
  35298. var geometry = (mesh.geometry);
  35299. if (this.storeEffectOnSubMeshes) {
  35300. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35301. var subMesh = _a[_i];
  35302. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35303. if (forceDisposeEffect && subMesh._materialEffect) {
  35304. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35305. }
  35306. }
  35307. }
  35308. else {
  35309. geometry._releaseVertexArrayObject(this._effect);
  35310. }
  35311. }
  35312. }
  35313. }
  35314. this._uniformBuffer.dispose();
  35315. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35316. if (forceDisposeEffect && this._effect) {
  35317. if (!this.storeEffectOnSubMeshes) {
  35318. this._scene.getEngine()._releaseEffect(this._effect);
  35319. }
  35320. this._effect = null;
  35321. }
  35322. // Callback
  35323. this.onDisposeObservable.notifyObservers(this);
  35324. this.onDisposeObservable.clear();
  35325. this.onBindObservable.clear();
  35326. this.onUnBindObservable.clear();
  35327. };
  35328. /**
  35329. * Serializes this material
  35330. * @returns the serialized material object
  35331. */
  35332. Material.prototype.serialize = function () {
  35333. return BABYLON.SerializationHelper.Serialize(this);
  35334. };
  35335. /**
  35336. * Creates a MultiMaterial from parsed MultiMaterial data.
  35337. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35338. * @param scene defines the hosting scene
  35339. * @returns a new MultiMaterial
  35340. */
  35341. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35342. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35343. multiMaterial.id = parsedMultiMaterial.id;
  35344. if (BABYLON.Tags) {
  35345. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35346. }
  35347. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35348. var subMatId = parsedMultiMaterial.materials[matIndex];
  35349. if (subMatId) {
  35350. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35351. }
  35352. else {
  35353. multiMaterial.subMaterials.push(null);
  35354. }
  35355. }
  35356. return multiMaterial;
  35357. };
  35358. /**
  35359. * Creates a material from parsed material data
  35360. * @param parsedMaterial defines parsed material data
  35361. * @param scene defines the hosting scene
  35362. * @param rootUrl defines the root URL to use to load textures
  35363. * @returns a new material
  35364. */
  35365. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35366. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35367. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35368. }
  35369. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35370. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35371. if (!BABYLON.LegacyPBRMaterial) {
  35372. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35373. return;
  35374. }
  35375. }
  35376. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35377. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35378. };
  35379. // Triangle views
  35380. Material._TriangleFillMode = 0;
  35381. Material._WireFrameFillMode = 1;
  35382. Material._PointFillMode = 2;
  35383. // Draw modes
  35384. Material._PointListDrawMode = 3;
  35385. Material._LineListDrawMode = 4;
  35386. Material._LineLoopDrawMode = 5;
  35387. Material._LineStripDrawMode = 6;
  35388. Material._TriangleStripDrawMode = 7;
  35389. Material._TriangleFanDrawMode = 8;
  35390. /**
  35391. * Stores the clock-wise side orientation
  35392. */
  35393. Material._ClockWiseSideOrientation = 0;
  35394. /**
  35395. * Stores the counter clock-wise side orientation
  35396. */
  35397. Material._CounterClockWiseSideOrientation = 1;
  35398. /**
  35399. * The dirty texture flag value
  35400. */
  35401. Material._TextureDirtyFlag = 1;
  35402. /**
  35403. * The dirty light flag value
  35404. */
  35405. Material._LightDirtyFlag = 2;
  35406. /**
  35407. * The dirty fresnel flag value
  35408. */
  35409. Material._FresnelDirtyFlag = 4;
  35410. /**
  35411. * The dirty attribute flag value
  35412. */
  35413. Material._AttributesDirtyFlag = 8;
  35414. /**
  35415. * The dirty misc flag value
  35416. */
  35417. Material._MiscDirtyFlag = 16;
  35418. __decorate([
  35419. BABYLON.serialize()
  35420. ], Material.prototype, "id", void 0);
  35421. __decorate([
  35422. BABYLON.serialize()
  35423. ], Material.prototype, "uniqueId", void 0);
  35424. __decorate([
  35425. BABYLON.serialize()
  35426. ], Material.prototype, "name", void 0);
  35427. __decorate([
  35428. BABYLON.serialize()
  35429. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35430. __decorate([
  35431. BABYLON.serialize()
  35432. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35433. __decorate([
  35434. BABYLON.serialize()
  35435. ], Material.prototype, "state", void 0);
  35436. __decorate([
  35437. BABYLON.serialize("alpha")
  35438. ], Material.prototype, "_alpha", void 0);
  35439. __decorate([
  35440. BABYLON.serialize("backFaceCulling")
  35441. ], Material.prototype, "_backFaceCulling", void 0);
  35442. __decorate([
  35443. BABYLON.serialize()
  35444. ], Material.prototype, "sideOrientation", void 0);
  35445. __decorate([
  35446. BABYLON.serialize("alphaMode")
  35447. ], Material.prototype, "_alphaMode", void 0);
  35448. __decorate([
  35449. BABYLON.serialize()
  35450. ], Material.prototype, "_needDepthPrePass", void 0);
  35451. __decorate([
  35452. BABYLON.serialize()
  35453. ], Material.prototype, "disableDepthWrite", void 0);
  35454. __decorate([
  35455. BABYLON.serialize()
  35456. ], Material.prototype, "forceDepthWrite", void 0);
  35457. __decorate([
  35458. BABYLON.serialize()
  35459. ], Material.prototype, "separateCullingPass", void 0);
  35460. __decorate([
  35461. BABYLON.serialize("fogEnabled")
  35462. ], Material.prototype, "_fogEnabled", void 0);
  35463. __decorate([
  35464. BABYLON.serialize()
  35465. ], Material.prototype, "pointSize", void 0);
  35466. __decorate([
  35467. BABYLON.serialize()
  35468. ], Material.prototype, "zOffset", void 0);
  35469. __decorate([
  35470. BABYLON.serialize()
  35471. ], Material.prototype, "wireframe", null);
  35472. __decorate([
  35473. BABYLON.serialize()
  35474. ], Material.prototype, "pointsCloud", null);
  35475. __decorate([
  35476. BABYLON.serialize()
  35477. ], Material.prototype, "fillMode", null);
  35478. return Material;
  35479. }());
  35480. BABYLON.Material = Material;
  35481. })(BABYLON || (BABYLON = {}));
  35482. //# sourceMappingURL=babylon.material.js.map
  35483. var BABYLON;
  35484. (function (BABYLON) {
  35485. var UniformBuffer = /** @class */ (function () {
  35486. /**
  35487. * Uniform buffer objects.
  35488. *
  35489. * Handles blocks of uniform on the GPU.
  35490. *
  35491. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35492. *
  35493. * For more information, please refer to :
  35494. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35495. */
  35496. function UniformBuffer(engine, data, dynamic) {
  35497. this._engine = engine;
  35498. this._noUBO = !engine.supportsUniformBuffers;
  35499. this._dynamic = dynamic;
  35500. this._data = data || [];
  35501. this._uniformLocations = {};
  35502. this._uniformSizes = {};
  35503. this._uniformLocationPointer = 0;
  35504. this._needSync = false;
  35505. if (this._noUBO) {
  35506. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35507. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35508. this.updateFloat = this._updateFloatForEffect;
  35509. this.updateFloat2 = this._updateFloat2ForEffect;
  35510. this.updateFloat3 = this._updateFloat3ForEffect;
  35511. this.updateFloat4 = this._updateFloat4ForEffect;
  35512. this.updateMatrix = this._updateMatrixForEffect;
  35513. this.updateVector3 = this._updateVector3ForEffect;
  35514. this.updateVector4 = this._updateVector4ForEffect;
  35515. this.updateColor3 = this._updateColor3ForEffect;
  35516. this.updateColor4 = this._updateColor4ForEffect;
  35517. }
  35518. else {
  35519. this._engine._uniformBuffers.push(this);
  35520. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35521. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35522. this.updateFloat = this._updateFloatForUniform;
  35523. this.updateFloat2 = this._updateFloat2ForUniform;
  35524. this.updateFloat3 = this._updateFloat3ForUniform;
  35525. this.updateFloat4 = this._updateFloat4ForUniform;
  35526. this.updateMatrix = this._updateMatrixForUniform;
  35527. this.updateVector3 = this._updateVector3ForUniform;
  35528. this.updateVector4 = this._updateVector4ForUniform;
  35529. this.updateColor3 = this._updateColor3ForUniform;
  35530. this.updateColor4 = this._updateColor4ForUniform;
  35531. }
  35532. }
  35533. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35534. // Properties
  35535. /**
  35536. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35537. * or just falling back on setUniformXXX calls.
  35538. */
  35539. get: function () {
  35540. return !this._noUBO;
  35541. },
  35542. enumerable: true,
  35543. configurable: true
  35544. });
  35545. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35546. /**
  35547. * Indicates if the WebGL underlying uniform buffer is in sync
  35548. * with the javascript cache data.
  35549. */
  35550. get: function () {
  35551. return !this._needSync;
  35552. },
  35553. enumerable: true,
  35554. configurable: true
  35555. });
  35556. /**
  35557. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35558. * Also, a dynamic UniformBuffer will disable cache verification and always
  35559. * update the underlying WebGL uniform buffer to the GPU.
  35560. */
  35561. UniformBuffer.prototype.isDynamic = function () {
  35562. return this._dynamic !== undefined;
  35563. };
  35564. /**
  35565. * The data cache on JS side.
  35566. */
  35567. UniformBuffer.prototype.getData = function () {
  35568. return this._bufferData;
  35569. };
  35570. /**
  35571. * The underlying WebGL Uniform buffer.
  35572. */
  35573. UniformBuffer.prototype.getBuffer = function () {
  35574. return this._buffer;
  35575. };
  35576. /**
  35577. * std140 layout specifies how to align data within an UBO structure.
  35578. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35579. * for specs.
  35580. */
  35581. UniformBuffer.prototype._fillAlignment = function (size) {
  35582. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35583. // and 4x4 matrices
  35584. // TODO : change if other types are used
  35585. var alignment;
  35586. if (size <= 2) {
  35587. alignment = size;
  35588. }
  35589. else {
  35590. alignment = 4;
  35591. }
  35592. if ((this._uniformLocationPointer % alignment) !== 0) {
  35593. var oldPointer = this._uniformLocationPointer;
  35594. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35595. var diff = this._uniformLocationPointer - oldPointer;
  35596. for (var i = 0; i < diff; i++) {
  35597. this._data.push(0);
  35598. }
  35599. }
  35600. };
  35601. /**
  35602. * Adds an uniform in the buffer.
  35603. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35604. * for the layout to be correct !
  35605. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35606. * @param {number|number[]} size Data size, or data directly.
  35607. */
  35608. UniformBuffer.prototype.addUniform = function (name, size) {
  35609. if (this._noUBO) {
  35610. return;
  35611. }
  35612. if (this._uniformLocations[name] !== undefined) {
  35613. // Already existing uniform
  35614. return;
  35615. }
  35616. // This function must be called in the order of the shader layout !
  35617. // size can be the size of the uniform, or data directly
  35618. var data;
  35619. if (size instanceof Array) {
  35620. data = size;
  35621. size = data.length;
  35622. }
  35623. else {
  35624. size = size;
  35625. data = [];
  35626. // Fill with zeros
  35627. for (var i = 0; i < size; i++) {
  35628. data.push(0);
  35629. }
  35630. }
  35631. this._fillAlignment(size);
  35632. this._uniformSizes[name] = size;
  35633. this._uniformLocations[name] = this._uniformLocationPointer;
  35634. this._uniformLocationPointer += size;
  35635. for (var i = 0; i < size; i++) {
  35636. this._data.push(data[i]);
  35637. }
  35638. this._needSync = true;
  35639. };
  35640. /**
  35641. * Wrapper for addUniform.
  35642. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35643. * @param {Matrix} mat A 4x4 matrix.
  35644. */
  35645. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35646. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35647. };
  35648. /**
  35649. * Wrapper for addUniform.
  35650. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35651. * @param {number} x
  35652. * @param {number} y
  35653. */
  35654. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35655. var temp = [x, y];
  35656. this.addUniform(name, temp);
  35657. };
  35658. /**
  35659. * Wrapper for addUniform.
  35660. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35661. * @param {number} x
  35662. * @param {number} y
  35663. * @param {number} z
  35664. */
  35665. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35666. var temp = [x, y, z];
  35667. this.addUniform(name, temp);
  35668. };
  35669. /**
  35670. * Wrapper for addUniform.
  35671. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35672. * @param {Color3} color
  35673. */
  35674. UniformBuffer.prototype.addColor3 = function (name, color) {
  35675. var temp = new Array();
  35676. color.toArray(temp);
  35677. this.addUniform(name, temp);
  35678. };
  35679. /**
  35680. * Wrapper for addUniform.
  35681. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35682. * @param {Color3} color
  35683. * @param {number} alpha
  35684. */
  35685. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35686. var temp = new Array();
  35687. color.toArray(temp);
  35688. temp.push(alpha);
  35689. this.addUniform(name, temp);
  35690. };
  35691. /**
  35692. * Wrapper for addUniform.
  35693. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35694. * @param {Vector3} vector
  35695. */
  35696. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35697. var temp = new Array();
  35698. vector.toArray(temp);
  35699. this.addUniform(name, temp);
  35700. };
  35701. /**
  35702. * Wrapper for addUniform.
  35703. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35704. */
  35705. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35706. this.addUniform(name, 12);
  35707. };
  35708. /**
  35709. * Wrapper for addUniform.
  35710. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35711. */
  35712. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35713. this.addUniform(name, 8);
  35714. };
  35715. /**
  35716. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35717. */
  35718. UniformBuffer.prototype.create = function () {
  35719. if (this._noUBO) {
  35720. return;
  35721. }
  35722. if (this._buffer) {
  35723. return; // nothing to do
  35724. }
  35725. // See spec, alignment must be filled as a vec4
  35726. this._fillAlignment(4);
  35727. this._bufferData = new Float32Array(this._data);
  35728. this._rebuild();
  35729. this._needSync = true;
  35730. };
  35731. UniformBuffer.prototype._rebuild = function () {
  35732. if (this._noUBO) {
  35733. return;
  35734. }
  35735. if (this._dynamic) {
  35736. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35737. }
  35738. else {
  35739. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35740. }
  35741. };
  35742. /**
  35743. * Updates the WebGL Uniform Buffer on the GPU.
  35744. * If the `dynamic` flag is set to true, no cache comparison is done.
  35745. * Otherwise, the buffer will be updated only if the cache differs.
  35746. */
  35747. UniformBuffer.prototype.update = function () {
  35748. if (!this._buffer) {
  35749. this.create();
  35750. return;
  35751. }
  35752. if (!this._dynamic && !this._needSync) {
  35753. return;
  35754. }
  35755. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35756. this._needSync = false;
  35757. };
  35758. /**
  35759. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35760. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35761. * @param {number[]|Float32Array} data Flattened data
  35762. * @param {number} size Size of the data.
  35763. */
  35764. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35765. var location = this._uniformLocations[uniformName];
  35766. if (location === undefined) {
  35767. if (this._buffer) {
  35768. // Cannot add an uniform if the buffer is already created
  35769. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35770. return;
  35771. }
  35772. this.addUniform(uniformName, size);
  35773. location = this._uniformLocations[uniformName];
  35774. }
  35775. if (!this._buffer) {
  35776. this.create();
  35777. }
  35778. if (!this._dynamic) {
  35779. // Cache for static uniform buffers
  35780. var changed = false;
  35781. for (var i = 0; i < size; i++) {
  35782. if (this._bufferData[location + i] !== data[i]) {
  35783. changed = true;
  35784. this._bufferData[location + i] = data[i];
  35785. }
  35786. }
  35787. this._needSync = this._needSync || changed;
  35788. }
  35789. else {
  35790. // No cache for dynamic
  35791. for (var i = 0; i < size; i++) {
  35792. this._bufferData[location + i] = data[i];
  35793. }
  35794. }
  35795. };
  35796. // Update methods
  35797. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35798. // To match std140, matrix must be realigned
  35799. for (var i = 0; i < 3; i++) {
  35800. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35801. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35802. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35803. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35804. }
  35805. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35806. };
  35807. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35808. this._currentEffect.setMatrix3x3(name, matrix);
  35809. };
  35810. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35811. this._currentEffect.setMatrix2x2(name, matrix);
  35812. };
  35813. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35814. // To match std140, matrix must be realigned
  35815. for (var i = 0; i < 2; i++) {
  35816. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35817. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35818. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35819. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35820. }
  35821. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35822. };
  35823. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35824. this._currentEffect.setFloat(name, x);
  35825. };
  35826. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35827. UniformBuffer._tempBuffer[0] = x;
  35828. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35829. };
  35830. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35831. if (suffix === void 0) { suffix = ""; }
  35832. this._currentEffect.setFloat2(name + suffix, x, y);
  35833. };
  35834. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35835. if (suffix === void 0) { suffix = ""; }
  35836. UniformBuffer._tempBuffer[0] = x;
  35837. UniformBuffer._tempBuffer[1] = y;
  35838. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35839. };
  35840. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35841. if (suffix === void 0) { suffix = ""; }
  35842. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35843. };
  35844. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35845. if (suffix === void 0) { suffix = ""; }
  35846. UniformBuffer._tempBuffer[0] = x;
  35847. UniformBuffer._tempBuffer[1] = y;
  35848. UniformBuffer._tempBuffer[2] = z;
  35849. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35850. };
  35851. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35852. if (suffix === void 0) { suffix = ""; }
  35853. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35854. };
  35855. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35856. if (suffix === void 0) { suffix = ""; }
  35857. UniformBuffer._tempBuffer[0] = x;
  35858. UniformBuffer._tempBuffer[1] = y;
  35859. UniformBuffer._tempBuffer[2] = z;
  35860. UniformBuffer._tempBuffer[3] = w;
  35861. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35862. };
  35863. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35864. this._currentEffect.setMatrix(name, mat);
  35865. };
  35866. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35867. this.updateUniform(name, mat.toArray(), 16);
  35868. };
  35869. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35870. this._currentEffect.setVector3(name, vector);
  35871. };
  35872. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35873. vector.toArray(UniformBuffer._tempBuffer);
  35874. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35875. };
  35876. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35877. this._currentEffect.setVector4(name, vector);
  35878. };
  35879. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35880. vector.toArray(UniformBuffer._tempBuffer);
  35881. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35882. };
  35883. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35884. if (suffix === void 0) { suffix = ""; }
  35885. this._currentEffect.setColor3(name + suffix, color);
  35886. };
  35887. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35888. if (suffix === void 0) { suffix = ""; }
  35889. color.toArray(UniformBuffer._tempBuffer);
  35890. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35891. };
  35892. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35893. if (suffix === void 0) { suffix = ""; }
  35894. this._currentEffect.setColor4(name + suffix, color, alpha);
  35895. };
  35896. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35897. if (suffix === void 0) { suffix = ""; }
  35898. color.toArray(UniformBuffer._tempBuffer);
  35899. UniformBuffer._tempBuffer[3] = alpha;
  35900. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35901. };
  35902. /**
  35903. * Sets a sampler uniform on the effect.
  35904. * @param {string} name Name of the sampler.
  35905. * @param {Texture} texture
  35906. */
  35907. UniformBuffer.prototype.setTexture = function (name, texture) {
  35908. this._currentEffect.setTexture(name, texture);
  35909. };
  35910. /**
  35911. * Directly updates the value of the uniform in the cache AND on the GPU.
  35912. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35913. * @param {number[]|Float32Array} data Flattened data
  35914. */
  35915. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35916. this.updateUniform(uniformName, data, data.length);
  35917. this.update();
  35918. };
  35919. /**
  35920. * Binds this uniform buffer to an effect.
  35921. * @param {Effect} effect
  35922. * @param {string} name Name of the uniform block in the shader.
  35923. */
  35924. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35925. this._currentEffect = effect;
  35926. if (this._noUBO || !this._buffer) {
  35927. return;
  35928. }
  35929. effect.bindUniformBuffer(this._buffer, name);
  35930. };
  35931. /**
  35932. * Disposes the uniform buffer.
  35933. */
  35934. UniformBuffer.prototype.dispose = function () {
  35935. if (this._noUBO) {
  35936. return;
  35937. }
  35938. var index = this._engine._uniformBuffers.indexOf(this);
  35939. if (index !== -1) {
  35940. this._engine._uniformBuffers.splice(index, 1);
  35941. }
  35942. if (!this._buffer) {
  35943. return;
  35944. }
  35945. if (this._engine._releaseBuffer(this._buffer)) {
  35946. this._buffer = null;
  35947. }
  35948. };
  35949. // Pool for avoiding memory leaks
  35950. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35951. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35952. return UniformBuffer;
  35953. }());
  35954. BABYLON.UniformBuffer = UniformBuffer;
  35955. })(BABYLON || (BABYLON = {}));
  35956. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35957. var BABYLON;
  35958. (function (BABYLON) {
  35959. /**
  35960. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35961. */
  35962. var VertexData = /** @class */ (function () {
  35963. function VertexData() {
  35964. }
  35965. /**
  35966. * Uses the passed data array to set the set the values for the specified kind of data
  35967. * @param data a linear array of floating numbers
  35968. * @param kind the type of data that is being set, eg positions, colors etc
  35969. */
  35970. VertexData.prototype.set = function (data, kind) {
  35971. switch (kind) {
  35972. case BABYLON.VertexBuffer.PositionKind:
  35973. this.positions = data;
  35974. break;
  35975. case BABYLON.VertexBuffer.NormalKind:
  35976. this.normals = data;
  35977. break;
  35978. case BABYLON.VertexBuffer.TangentKind:
  35979. this.tangents = data;
  35980. break;
  35981. case BABYLON.VertexBuffer.UVKind:
  35982. this.uvs = data;
  35983. break;
  35984. case BABYLON.VertexBuffer.UV2Kind:
  35985. this.uvs2 = data;
  35986. break;
  35987. case BABYLON.VertexBuffer.UV3Kind:
  35988. this.uvs3 = data;
  35989. break;
  35990. case BABYLON.VertexBuffer.UV4Kind:
  35991. this.uvs4 = data;
  35992. break;
  35993. case BABYLON.VertexBuffer.UV5Kind:
  35994. this.uvs5 = data;
  35995. break;
  35996. case BABYLON.VertexBuffer.UV6Kind:
  35997. this.uvs6 = data;
  35998. break;
  35999. case BABYLON.VertexBuffer.ColorKind:
  36000. this.colors = data;
  36001. break;
  36002. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36003. this.matricesIndices = data;
  36004. break;
  36005. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36006. this.matricesWeights = data;
  36007. break;
  36008. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36009. this.matricesIndicesExtra = data;
  36010. break;
  36011. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36012. this.matricesWeightsExtra = data;
  36013. break;
  36014. }
  36015. };
  36016. /**
  36017. * Associates the vertexData to the passed Mesh.
  36018. * Sets it as updatable or not (default `false`)
  36019. * @param mesh the mesh the vertexData is applied to
  36020. * @param updatable when used and having the value true allows new data to update the vertexData
  36021. * @returns the VertexData
  36022. */
  36023. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36024. this._applyTo(mesh, updatable);
  36025. return this;
  36026. };
  36027. /**
  36028. * Associates the vertexData to the passed Geometry.
  36029. * Sets it as updatable or not (default `false`)
  36030. * @param geometry the geometry the vertexData is applied to
  36031. * @param updatable when used and having the value true allows new data to update the vertexData
  36032. * @returns VertexData
  36033. */
  36034. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36035. this._applyTo(geometry, updatable);
  36036. return this;
  36037. };
  36038. /**
  36039. * Updates the associated mesh
  36040. * @param mesh the mesh to be updated
  36041. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36042. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36043. * @returns VertexData
  36044. */
  36045. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36046. this._update(mesh);
  36047. return this;
  36048. };
  36049. /**
  36050. * Updates the associated geometry
  36051. * @param geometry the geometry to be updated
  36052. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36053. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36054. * @returns VertexData.
  36055. */
  36056. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36057. this._update(geometry);
  36058. return this;
  36059. };
  36060. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36061. if (updatable === void 0) { updatable = false; }
  36062. if (this.positions) {
  36063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36064. }
  36065. if (this.normals) {
  36066. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36067. }
  36068. if (this.tangents) {
  36069. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36070. }
  36071. if (this.uvs) {
  36072. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36073. }
  36074. if (this.uvs2) {
  36075. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36076. }
  36077. if (this.uvs3) {
  36078. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36079. }
  36080. if (this.uvs4) {
  36081. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36082. }
  36083. if (this.uvs5) {
  36084. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36085. }
  36086. if (this.uvs6) {
  36087. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36088. }
  36089. if (this.colors) {
  36090. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36091. }
  36092. if (this.matricesIndices) {
  36093. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36094. }
  36095. if (this.matricesWeights) {
  36096. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36097. }
  36098. if (this.matricesIndicesExtra) {
  36099. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36100. }
  36101. if (this.matricesWeightsExtra) {
  36102. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36103. }
  36104. if (this.indices) {
  36105. meshOrGeometry.setIndices(this.indices, null, updatable);
  36106. }
  36107. else {
  36108. meshOrGeometry.setIndices([], null);
  36109. }
  36110. return this;
  36111. };
  36112. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36113. if (this.positions) {
  36114. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36115. }
  36116. if (this.normals) {
  36117. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36118. }
  36119. if (this.tangents) {
  36120. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36121. }
  36122. if (this.uvs) {
  36123. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36124. }
  36125. if (this.uvs2) {
  36126. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36127. }
  36128. if (this.uvs3) {
  36129. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36130. }
  36131. if (this.uvs4) {
  36132. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36133. }
  36134. if (this.uvs5) {
  36135. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36136. }
  36137. if (this.uvs6) {
  36138. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36139. }
  36140. if (this.colors) {
  36141. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36142. }
  36143. if (this.matricesIndices) {
  36144. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36145. }
  36146. if (this.matricesWeights) {
  36147. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36148. }
  36149. if (this.matricesIndicesExtra) {
  36150. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36151. }
  36152. if (this.matricesWeightsExtra) {
  36153. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36154. }
  36155. if (this.indices) {
  36156. meshOrGeometry.setIndices(this.indices, null);
  36157. }
  36158. return this;
  36159. };
  36160. /**
  36161. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36162. * @param matrix the transforming matrix
  36163. * @returns the VertexData
  36164. */
  36165. VertexData.prototype.transform = function (matrix) {
  36166. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36167. var transformed = BABYLON.Vector3.Zero();
  36168. var index;
  36169. if (this.positions) {
  36170. var position = BABYLON.Vector3.Zero();
  36171. for (index = 0; index < this.positions.length; index += 3) {
  36172. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36173. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36174. this.positions[index] = transformed.x;
  36175. this.positions[index + 1] = transformed.y;
  36176. this.positions[index + 2] = transformed.z;
  36177. }
  36178. }
  36179. if (this.normals) {
  36180. var normal = BABYLON.Vector3.Zero();
  36181. for (index = 0; index < this.normals.length; index += 3) {
  36182. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36183. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36184. this.normals[index] = transformed.x;
  36185. this.normals[index + 1] = transformed.y;
  36186. this.normals[index + 2] = transformed.z;
  36187. }
  36188. }
  36189. if (this.tangents) {
  36190. var tangent = BABYLON.Vector4.Zero();
  36191. var tangentTransformed = BABYLON.Vector4.Zero();
  36192. for (index = 0; index < this.tangents.length; index += 4) {
  36193. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36194. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36195. this.tangents[index] = tangentTransformed.x;
  36196. this.tangents[index + 1] = tangentTransformed.y;
  36197. this.tangents[index + 2] = tangentTransformed.z;
  36198. this.tangents[index + 3] = tangentTransformed.w;
  36199. }
  36200. }
  36201. if (flip && this.indices) {
  36202. for (index = 0; index < this.indices.length; index += 3) {
  36203. var tmp = this.indices[index + 1];
  36204. this.indices[index + 1] = this.indices[index + 2];
  36205. this.indices[index + 2] = tmp;
  36206. }
  36207. }
  36208. return this;
  36209. };
  36210. /**
  36211. * Merges the passed VertexData into the current one
  36212. * @param other the VertexData to be merged into the current one
  36213. * @returns the modified VertexData
  36214. */
  36215. VertexData.prototype.merge = function (other) {
  36216. this._validate();
  36217. other._validate();
  36218. if (!this.normals !== !other.normals ||
  36219. !this.tangents !== !other.tangents ||
  36220. !this.uvs !== !other.uvs ||
  36221. !this.uvs2 !== !other.uvs2 ||
  36222. !this.uvs3 !== !other.uvs3 ||
  36223. !this.uvs4 !== !other.uvs4 ||
  36224. !this.uvs5 !== !other.uvs5 ||
  36225. !this.uvs6 !== !other.uvs6 ||
  36226. !this.colors !== !other.colors ||
  36227. !this.matricesIndices !== !other.matricesIndices ||
  36228. !this.matricesWeights !== !other.matricesWeights ||
  36229. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36230. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36231. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36232. }
  36233. if (other.indices) {
  36234. if (!this.indices) {
  36235. this.indices = [];
  36236. }
  36237. var offset = this.positions ? this.positions.length / 3 : 0;
  36238. for (var index = 0; index < other.indices.length; index++) {
  36239. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36240. this.indices.push(other.indices[index] + offset);
  36241. }
  36242. }
  36243. this.positions = this._mergeElement(this.positions, other.positions);
  36244. this.normals = this._mergeElement(this.normals, other.normals);
  36245. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36246. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36247. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36248. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36249. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36250. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36251. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36252. this.colors = this._mergeElement(this.colors, other.colors);
  36253. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36254. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36255. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36256. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36257. return this;
  36258. };
  36259. VertexData.prototype._mergeElement = function (source, other) {
  36260. if (!source) {
  36261. return other;
  36262. }
  36263. if (!other) {
  36264. return source;
  36265. }
  36266. var len = other.length + source.length;
  36267. var isSrcTypedArray = source instanceof Float32Array;
  36268. var isOthTypedArray = other instanceof Float32Array;
  36269. // use non-loop method when the source is Float32Array
  36270. if (isSrcTypedArray) {
  36271. var ret32 = new Float32Array(len);
  36272. ret32.set(source);
  36273. ret32.set(other, source.length);
  36274. return ret32;
  36275. // source is number[], when other is also use concat
  36276. }
  36277. else if (!isOthTypedArray) {
  36278. return source.concat(other);
  36279. // source is a number[], but other is a Float32Array, loop required
  36280. }
  36281. else {
  36282. var ret = source.slice(0); // copy source to a separate array
  36283. for (var i = 0, len = other.length; i < len; i++) {
  36284. ret.push(other[i]);
  36285. }
  36286. return ret;
  36287. }
  36288. };
  36289. VertexData.prototype._validate = function () {
  36290. if (!this.positions) {
  36291. throw new Error("Positions are required");
  36292. }
  36293. var getElementCount = function (kind, values) {
  36294. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36295. if ((values.length % stride) !== 0) {
  36296. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36297. }
  36298. return values.length / stride;
  36299. };
  36300. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36301. var validateElementCount = function (kind, values) {
  36302. var elementCount = getElementCount(kind, values);
  36303. if (elementCount !== positionsElementCount) {
  36304. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36305. }
  36306. };
  36307. if (this.normals)
  36308. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36309. if (this.tangents)
  36310. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36311. if (this.uvs)
  36312. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36313. if (this.uvs2)
  36314. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36315. if (this.uvs3)
  36316. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36317. if (this.uvs4)
  36318. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36319. if (this.uvs5)
  36320. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36321. if (this.uvs6)
  36322. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36323. if (this.colors)
  36324. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36325. if (this.matricesIndices)
  36326. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36327. if (this.matricesWeights)
  36328. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36329. if (this.matricesIndicesExtra)
  36330. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36331. if (this.matricesWeightsExtra)
  36332. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36333. };
  36334. /**
  36335. * Serializes the VertexData
  36336. * @returns a serialized object
  36337. */
  36338. VertexData.prototype.serialize = function () {
  36339. var serializationObject = this.serialize();
  36340. if (this.positions) {
  36341. serializationObject.positions = this.positions;
  36342. }
  36343. if (this.normals) {
  36344. serializationObject.normals = this.normals;
  36345. }
  36346. if (this.tangents) {
  36347. serializationObject.tangents = this.tangents;
  36348. }
  36349. if (this.uvs) {
  36350. serializationObject.uvs = this.uvs;
  36351. }
  36352. if (this.uvs2) {
  36353. serializationObject.uvs2 = this.uvs2;
  36354. }
  36355. if (this.uvs3) {
  36356. serializationObject.uvs3 = this.uvs3;
  36357. }
  36358. if (this.uvs4) {
  36359. serializationObject.uvs4 = this.uvs4;
  36360. }
  36361. if (this.uvs5) {
  36362. serializationObject.uvs5 = this.uvs5;
  36363. }
  36364. if (this.uvs6) {
  36365. serializationObject.uvs6 = this.uvs6;
  36366. }
  36367. if (this.colors) {
  36368. serializationObject.colors = this.colors;
  36369. }
  36370. if (this.matricesIndices) {
  36371. serializationObject.matricesIndices = this.matricesIndices;
  36372. serializationObject.matricesIndices._isExpanded = true;
  36373. }
  36374. if (this.matricesWeights) {
  36375. serializationObject.matricesWeights = this.matricesWeights;
  36376. }
  36377. if (this.matricesIndicesExtra) {
  36378. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36379. serializationObject.matricesIndicesExtra._isExpanded = true;
  36380. }
  36381. if (this.matricesWeightsExtra) {
  36382. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36383. }
  36384. serializationObject.indices = this.indices;
  36385. return serializationObject;
  36386. };
  36387. // Statics
  36388. /**
  36389. * Extracts the vertexData from a mesh
  36390. * @param mesh the mesh from which to extract the VertexData
  36391. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36392. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36393. * @returns the object VertexData associated to the passed mesh
  36394. */
  36395. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36396. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36397. };
  36398. /**
  36399. * Extracts the vertexData from the geometry
  36400. * @param geometry the geometry from which to extract the VertexData
  36401. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36402. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36403. * @returns the object VertexData associated to the passed mesh
  36404. */
  36405. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36406. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36407. };
  36408. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36409. var result = new VertexData();
  36410. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36411. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36412. }
  36413. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36414. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36415. }
  36416. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36417. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36418. }
  36419. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36420. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36421. }
  36422. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36423. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36424. }
  36425. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36426. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36427. }
  36428. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36429. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36430. }
  36431. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36432. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36433. }
  36434. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36435. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36436. }
  36437. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36438. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36439. }
  36440. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36441. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36442. }
  36443. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36444. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36445. }
  36446. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36447. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36448. }
  36449. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36450. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36451. }
  36452. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36453. return result;
  36454. };
  36455. /**
  36456. * Creates the VertexData for a Ribbon
  36457. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36458. * * pathArray array of paths, each of which an array of successive Vector3
  36459. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36460. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36461. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36462. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36463. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36464. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36465. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36466. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36467. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36468. * @returns the VertexData of the ribbon
  36469. */
  36470. VertexData.CreateRibbon = function (options) {
  36471. var pathArray = options.pathArray;
  36472. var closeArray = options.closeArray || false;
  36473. var closePath = options.closePath || false;
  36474. var invertUV = options.invertUV || false;
  36475. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36476. var offset = options.offset || defaultOffset;
  36477. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36478. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36479. var customUV = options.uvs;
  36480. var customColors = options.colors;
  36481. var positions = [];
  36482. var indices = [];
  36483. var normals = [];
  36484. var uvs = [];
  36485. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36486. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36487. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36488. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36489. var minlg; // minimal length among all paths from pathArray
  36490. var lg = []; // array of path lengths : nb of vertex per path
  36491. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36492. var p; // path iterator
  36493. var i; // point iterator
  36494. var j; // point iterator
  36495. // if single path in pathArray
  36496. if (pathArray.length < 2) {
  36497. var ar1 = [];
  36498. var ar2 = [];
  36499. for (i = 0; i < pathArray[0].length - offset; i++) {
  36500. ar1.push(pathArray[0][i]);
  36501. ar2.push(pathArray[0][i + offset]);
  36502. }
  36503. pathArray = [ar1, ar2];
  36504. }
  36505. // positions and horizontal distances (u)
  36506. var idc = 0;
  36507. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36508. var path;
  36509. var l;
  36510. minlg = pathArray[0].length;
  36511. var vectlg;
  36512. var dist;
  36513. for (p = 0; p < pathArray.length; p++) {
  36514. uTotalDistance[p] = 0;
  36515. us[p] = [0];
  36516. path = pathArray[p];
  36517. l = path.length;
  36518. minlg = (minlg < l) ? minlg : l;
  36519. j = 0;
  36520. while (j < l) {
  36521. positions.push(path[j].x, path[j].y, path[j].z);
  36522. if (j > 0) {
  36523. vectlg = path[j].subtract(path[j - 1]).length();
  36524. dist = vectlg + uTotalDistance[p];
  36525. us[p].push(dist);
  36526. uTotalDistance[p] = dist;
  36527. }
  36528. j++;
  36529. }
  36530. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36531. j--;
  36532. positions.push(path[0].x, path[0].y, path[0].z);
  36533. vectlg = path[j].subtract(path[0]).length();
  36534. dist = vectlg + uTotalDistance[p];
  36535. us[p].push(dist);
  36536. uTotalDistance[p] = dist;
  36537. }
  36538. lg[p] = l + closePathCorr;
  36539. idx[p] = idc;
  36540. idc += (l + closePathCorr);
  36541. }
  36542. // vertical distances (v)
  36543. var path1;
  36544. var path2;
  36545. var vertex1 = null;
  36546. var vertex2 = null;
  36547. for (i = 0; i < minlg + closePathCorr; i++) {
  36548. vTotalDistance[i] = 0;
  36549. vs[i] = [0];
  36550. for (p = 0; p < pathArray.length - 1; p++) {
  36551. path1 = pathArray[p];
  36552. path2 = pathArray[p + 1];
  36553. if (i === minlg) { // closePath
  36554. vertex1 = path1[0];
  36555. vertex2 = path2[0];
  36556. }
  36557. else {
  36558. vertex1 = path1[i];
  36559. vertex2 = path2[i];
  36560. }
  36561. vectlg = vertex2.subtract(vertex1).length();
  36562. dist = vectlg + vTotalDistance[i];
  36563. vs[i].push(dist);
  36564. vTotalDistance[i] = dist;
  36565. }
  36566. if (closeArray && vertex2 && vertex1) {
  36567. path1 = pathArray[p];
  36568. path2 = pathArray[0];
  36569. if (i === minlg) { // closePath
  36570. vertex2 = path2[0];
  36571. }
  36572. vectlg = vertex2.subtract(vertex1).length();
  36573. dist = vectlg + vTotalDistance[i];
  36574. vTotalDistance[i] = dist;
  36575. }
  36576. }
  36577. // uvs
  36578. var u;
  36579. var v;
  36580. if (customUV) {
  36581. for (p = 0; p < customUV.length; p++) {
  36582. uvs.push(customUV[p].x, customUV[p].y);
  36583. }
  36584. }
  36585. else {
  36586. for (p = 0; p < pathArray.length; p++) {
  36587. for (i = 0; i < minlg + closePathCorr; i++) {
  36588. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36589. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36590. if (invertUV) {
  36591. uvs.push(v, u);
  36592. }
  36593. else {
  36594. uvs.push(u, v);
  36595. }
  36596. }
  36597. }
  36598. }
  36599. // indices
  36600. p = 0; // path index
  36601. var pi = 0; // positions array index
  36602. var l1 = lg[p] - 1; // path1 length
  36603. var l2 = lg[p + 1] - 1; // path2 length
  36604. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36605. var shft = idx[1] - idx[0]; // shift
  36606. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36607. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36608. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  36609. indices.push(pi, pi + shft, pi + 1);
  36610. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36611. pi += 1;
  36612. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36613. p++;
  36614. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36615. shft = idx[0] - idx[p];
  36616. l1 = lg[p] - 1;
  36617. l2 = lg[0] - 1;
  36618. }
  36619. else {
  36620. shft = idx[p + 1] - idx[p];
  36621. l1 = lg[p] - 1;
  36622. l2 = lg[p + 1] - 1;
  36623. }
  36624. pi = idx[p];
  36625. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36626. }
  36627. }
  36628. // normals
  36629. VertexData.ComputeNormals(positions, indices, normals);
  36630. if (closePath) { // update both the first and last vertex normals to their average value
  36631. var indexFirst = 0;
  36632. var indexLast = 0;
  36633. for (p = 0; p < pathArray.length; p++) {
  36634. indexFirst = idx[p] * 3;
  36635. if (p + 1 < pathArray.length) {
  36636. indexLast = (idx[p + 1] - 1) * 3;
  36637. }
  36638. else {
  36639. indexLast = normals.length - 3;
  36640. }
  36641. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36642. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36643. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36644. normals[indexLast] = normals[indexFirst];
  36645. normals[indexLast + 1] = normals[indexFirst + 1];
  36646. normals[indexLast + 2] = normals[indexFirst + 2];
  36647. }
  36648. }
  36649. // sides
  36650. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36651. // Colors
  36652. var colors = null;
  36653. if (customColors) {
  36654. colors = new Float32Array(customColors.length * 4);
  36655. for (var c = 0; c < customColors.length; c++) {
  36656. colors[c * 4] = customColors[c].r;
  36657. colors[c * 4 + 1] = customColors[c].g;
  36658. colors[c * 4 + 2] = customColors[c].b;
  36659. colors[c * 4 + 3] = customColors[c].a;
  36660. }
  36661. }
  36662. // Result
  36663. var vertexData = new VertexData();
  36664. var positions32 = new Float32Array(positions);
  36665. var normals32 = new Float32Array(normals);
  36666. var uvs32 = new Float32Array(uvs);
  36667. vertexData.indices = indices;
  36668. vertexData.positions = positions32;
  36669. vertexData.normals = normals32;
  36670. vertexData.uvs = uvs32;
  36671. if (colors) {
  36672. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36673. }
  36674. if (closePath) {
  36675. vertexData._idx = idx;
  36676. }
  36677. return vertexData;
  36678. };
  36679. /**
  36680. * Creates the VertexData for a box
  36681. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36682. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36683. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36684. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36685. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36686. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36687. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36688. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36689. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36690. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36691. * @returns the VertexData of the box
  36692. */
  36693. VertexData.CreateBox = function (options) {
  36694. var normalsSource = [
  36695. new BABYLON.Vector3(0, 0, 1),
  36696. new BABYLON.Vector3(0, 0, -1),
  36697. new BABYLON.Vector3(1, 0, 0),
  36698. new BABYLON.Vector3(-1, 0, 0),
  36699. new BABYLON.Vector3(0, 1, 0),
  36700. new BABYLON.Vector3(0, -1, 0)
  36701. ];
  36702. var indices = [];
  36703. var positions = [];
  36704. var normals = [];
  36705. var uvs = [];
  36706. var width = options.width || options.size || 1;
  36707. var height = options.height || options.size || 1;
  36708. var depth = options.depth || options.size || 1;
  36709. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36710. var faceUV = options.faceUV || new Array(6);
  36711. var faceColors = options.faceColors;
  36712. var colors = [];
  36713. // default face colors and UV if undefined
  36714. for (var f = 0; f < 6; f++) {
  36715. if (faceUV[f] === undefined) {
  36716. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36717. }
  36718. if (faceColors && faceColors[f] === undefined) {
  36719. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36720. }
  36721. }
  36722. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36723. // Create each face in turn.
  36724. for (var index = 0; index < normalsSource.length; index++) {
  36725. var normal = normalsSource[index];
  36726. // Get two vectors perpendicular to the face normal and to each other.
  36727. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36728. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36729. // Six indices (two triangles) per face.
  36730. var verticesLength = positions.length / 3;
  36731. indices.push(verticesLength);
  36732. indices.push(verticesLength + 1);
  36733. indices.push(verticesLength + 2);
  36734. indices.push(verticesLength);
  36735. indices.push(verticesLength + 2);
  36736. indices.push(verticesLength + 3);
  36737. // Four vertices per face.
  36738. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36739. positions.push(vertex.x, vertex.y, vertex.z);
  36740. normals.push(normal.x, normal.y, normal.z);
  36741. uvs.push(faceUV[index].z, faceUV[index].w);
  36742. if (faceColors) {
  36743. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36744. }
  36745. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36746. positions.push(vertex.x, vertex.y, vertex.z);
  36747. normals.push(normal.x, normal.y, normal.z);
  36748. uvs.push(faceUV[index].x, faceUV[index].w);
  36749. if (faceColors) {
  36750. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36751. }
  36752. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36753. positions.push(vertex.x, vertex.y, vertex.z);
  36754. normals.push(normal.x, normal.y, normal.z);
  36755. uvs.push(faceUV[index].x, faceUV[index].y);
  36756. if (faceColors) {
  36757. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36758. }
  36759. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36760. positions.push(vertex.x, vertex.y, vertex.z);
  36761. normals.push(normal.x, normal.y, normal.z);
  36762. uvs.push(faceUV[index].z, faceUV[index].y);
  36763. if (faceColors) {
  36764. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36765. }
  36766. }
  36767. // sides
  36768. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36769. // Result
  36770. var vertexData = new VertexData();
  36771. vertexData.indices = indices;
  36772. vertexData.positions = positions;
  36773. vertexData.normals = normals;
  36774. vertexData.uvs = uvs;
  36775. if (faceColors) {
  36776. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36777. vertexData.colors = totalColors;
  36778. }
  36779. return vertexData;
  36780. };
  36781. /**
  36782. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36783. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36784. * * segments sets the number of horizontal strips optional, default 32
  36785. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36786. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36787. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36788. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36789. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36790. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36791. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36792. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36793. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36794. * @returns the VertexData of the ellipsoid
  36795. */
  36796. VertexData.CreateSphere = function (options) {
  36797. var segments = options.segments || 32;
  36798. var diameterX = options.diameterX || options.diameter || 1;
  36799. var diameterY = options.diameterY || options.diameter || 1;
  36800. var diameterZ = options.diameterZ || options.diameter || 1;
  36801. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36802. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36803. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36804. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36805. var totalZRotationSteps = 2 + segments;
  36806. var totalYRotationSteps = 2 * totalZRotationSteps;
  36807. var indices = [];
  36808. var positions = [];
  36809. var normals = [];
  36810. var uvs = [];
  36811. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36812. var normalizedZ = zRotationStep / totalZRotationSteps;
  36813. var angleZ = normalizedZ * Math.PI * slice;
  36814. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36815. var normalizedY = yRotationStep / totalYRotationSteps;
  36816. var angleY = normalizedY * Math.PI * 2 * arc;
  36817. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36818. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36819. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36820. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36821. var vertex = complete.multiply(radius);
  36822. var normal = complete.divide(radius).normalize();
  36823. positions.push(vertex.x, vertex.y, vertex.z);
  36824. normals.push(normal.x, normal.y, normal.z);
  36825. uvs.push(normalizedY, normalizedZ);
  36826. }
  36827. if (zRotationStep > 0) {
  36828. var verticesCount = positions.length / 3;
  36829. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36830. indices.push((firstIndex));
  36831. indices.push((firstIndex + 1));
  36832. indices.push(firstIndex + totalYRotationSteps + 1);
  36833. indices.push((firstIndex + totalYRotationSteps + 1));
  36834. indices.push((firstIndex + 1));
  36835. indices.push((firstIndex + totalYRotationSteps + 2));
  36836. }
  36837. }
  36838. }
  36839. // Sides
  36840. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36841. // Result
  36842. var vertexData = new VertexData();
  36843. vertexData.indices = indices;
  36844. vertexData.positions = positions;
  36845. vertexData.normals = normals;
  36846. vertexData.uvs = uvs;
  36847. return vertexData;
  36848. };
  36849. /**
  36850. * Creates the VertexData for a cylinder, cone or prism
  36851. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36852. * * height sets the height (y direction) of the cylinder, optional, default 2
  36853. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36854. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36855. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36856. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36857. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36858. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  36859. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36860. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36861. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36862. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36863. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36864. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36865. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36866. * @returns the VertexData of the cylinder, cone or prism
  36867. */
  36868. VertexData.CreateCylinder = function (options) {
  36869. var height = options.height || 2;
  36870. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36871. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36872. var tessellation = options.tessellation || 24;
  36873. var subdivisions = options.subdivisions || 1;
  36874. var hasRings = options.hasRings ? true : false;
  36875. var enclose = options.enclose ? true : false;
  36876. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36877. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36878. var faceUV = options.faceUV || new Array(3);
  36879. var faceColors = options.faceColors;
  36880. // default face colors and UV if undefined
  36881. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36882. var ringNb = (hasRings) ? subdivisions : 1;
  36883. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36884. var f;
  36885. for (f = 0; f < surfaceNb; f++) {
  36886. if (faceColors && faceColors[f] === undefined) {
  36887. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36888. }
  36889. }
  36890. for (f = 0; f < surfaceNb; f++) {
  36891. if (faceUV && faceUV[f] === undefined) {
  36892. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36893. }
  36894. }
  36895. var indices = new Array();
  36896. var positions = new Array();
  36897. var normals = new Array();
  36898. var uvs = new Array();
  36899. var colors = new Array();
  36900. var angle_step = Math.PI * 2 * arc / tessellation;
  36901. var angle;
  36902. var h;
  36903. var radius;
  36904. var tan = (diameterBottom - diameterTop) / 2 / height;
  36905. var ringVertex = BABYLON.Vector3.Zero();
  36906. var ringNormal = BABYLON.Vector3.Zero();
  36907. var ringFirstVertex = BABYLON.Vector3.Zero();
  36908. var ringFirstNormal = BABYLON.Vector3.Zero();
  36909. var quadNormal = BABYLON.Vector3.Zero();
  36910. var Y = BABYLON.Axis.Y;
  36911. // positions, normals, uvs
  36912. var i;
  36913. var j;
  36914. var r;
  36915. var ringIdx = 1;
  36916. var s = 1; // surface index
  36917. var cs = 0;
  36918. var v = 0;
  36919. for (i = 0; i <= subdivisions; i++) {
  36920. h = i / subdivisions;
  36921. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36922. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36923. for (r = 0; r < ringIdx; r++) {
  36924. if (hasRings) {
  36925. s += r;
  36926. }
  36927. if (enclose) {
  36928. s += 2 * r;
  36929. }
  36930. for (j = 0; j <= tessellation; j++) {
  36931. angle = j * angle_step;
  36932. // position
  36933. ringVertex.x = Math.cos(-angle) * radius;
  36934. ringVertex.y = -height / 2 + h * height;
  36935. ringVertex.z = Math.sin(-angle) * radius;
  36936. // normal
  36937. if (diameterTop === 0 && i === subdivisions) {
  36938. // if no top cap, reuse former normals
  36939. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36940. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36941. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36942. }
  36943. else {
  36944. ringNormal.x = ringVertex.x;
  36945. ringNormal.z = ringVertex.z;
  36946. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36947. ringNormal.normalize();
  36948. }
  36949. // keep first ring vertex values for enclose
  36950. if (j === 0) {
  36951. ringFirstVertex.copyFrom(ringVertex);
  36952. ringFirstNormal.copyFrom(ringNormal);
  36953. }
  36954. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36955. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36956. if (hasRings) {
  36957. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36958. }
  36959. else {
  36960. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36961. }
  36962. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36963. if (faceColors) {
  36964. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36965. }
  36966. }
  36967. // if enclose, add four vertices and their dedicated normals
  36968. if (arc !== 1 && enclose) {
  36969. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36970. positions.push(0, ringVertex.y, 0);
  36971. positions.push(0, ringVertex.y, 0);
  36972. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36973. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36974. quadNormal.normalize();
  36975. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36976. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36977. quadNormal.normalize();
  36978. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36979. if (hasRings) {
  36980. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36981. }
  36982. else {
  36983. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36984. }
  36985. uvs.push(faceUV[s + 1].x, v);
  36986. uvs.push(faceUV[s + 1].z, v);
  36987. if (hasRings) {
  36988. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36989. }
  36990. else {
  36991. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36992. }
  36993. uvs.push(faceUV[s + 2].x, v);
  36994. uvs.push(faceUV[s + 2].z, v);
  36995. if (faceColors) {
  36996. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36997. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36998. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36999. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37000. }
  37001. }
  37002. if (cs !== s) {
  37003. cs = s;
  37004. }
  37005. }
  37006. }
  37007. // indices
  37008. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37009. var s;
  37010. i = 0;
  37011. for (s = 0; s < subdivisions; s++) {
  37012. var i0 = 0;
  37013. var i1 = 0;
  37014. var i2 = 0;
  37015. var i3 = 0;
  37016. for (j = 0; j < tessellation; j++) {
  37017. i0 = i * (e + 1) + j;
  37018. i1 = (i + 1) * (e + 1) + j;
  37019. i2 = i * (e + 1) + (j + 1);
  37020. i3 = (i + 1) * (e + 1) + (j + 1);
  37021. indices.push(i0, i1, i2);
  37022. indices.push(i3, i2, i1);
  37023. }
  37024. if (arc !== 1 && enclose) { // if enclose, add two quads
  37025. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37026. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37027. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37028. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37029. }
  37030. i = (hasRings) ? (i + 2) : (i + 1);
  37031. }
  37032. // Caps
  37033. var createCylinderCap = function (isTop) {
  37034. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37035. if (radius === 0) {
  37036. return;
  37037. }
  37038. // Cap positions, normals & uvs
  37039. var angle;
  37040. var circleVector;
  37041. var i;
  37042. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37043. var c = null;
  37044. if (faceColors) {
  37045. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37046. }
  37047. // cap center
  37048. var vbase = positions.length / 3;
  37049. var offset = isTop ? height / 2 : -height / 2;
  37050. var center = new BABYLON.Vector3(0, offset, 0);
  37051. positions.push(center.x, center.y, center.z);
  37052. normals.push(0, isTop ? 1 : -1, 0);
  37053. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37054. if (c) {
  37055. colors.push(c.r, c.g, c.b, c.a);
  37056. }
  37057. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37058. for (i = 0; i <= tessellation; i++) {
  37059. angle = Math.PI * 2 * i * arc / tessellation;
  37060. var cos = Math.cos(-angle);
  37061. var sin = Math.sin(-angle);
  37062. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37063. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37064. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37065. normals.push(0, isTop ? 1 : -1, 0);
  37066. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37067. if (c) {
  37068. colors.push(c.r, c.g, c.b, c.a);
  37069. }
  37070. }
  37071. // Cap indices
  37072. for (i = 0; i < tessellation; i++) {
  37073. if (!isTop) {
  37074. indices.push(vbase);
  37075. indices.push(vbase + (i + 1));
  37076. indices.push(vbase + (i + 2));
  37077. }
  37078. else {
  37079. indices.push(vbase);
  37080. indices.push(vbase + (i + 2));
  37081. indices.push(vbase + (i + 1));
  37082. }
  37083. }
  37084. };
  37085. // add caps to geometry
  37086. createCylinderCap(false);
  37087. createCylinderCap(true);
  37088. // Sides
  37089. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37090. var vertexData = new VertexData();
  37091. vertexData.indices = indices;
  37092. vertexData.positions = positions;
  37093. vertexData.normals = normals;
  37094. vertexData.uvs = uvs;
  37095. if (faceColors) {
  37096. vertexData.colors = colors;
  37097. }
  37098. return vertexData;
  37099. };
  37100. /**
  37101. * Creates the VertexData for a torus
  37102. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37103. * * diameter the diameter of the torus, optional default 1
  37104. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37105. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37106. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37107. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37108. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37109. * @returns the VertexData of the torus
  37110. */
  37111. VertexData.CreateTorus = function (options) {
  37112. var indices = [];
  37113. var positions = [];
  37114. var normals = [];
  37115. var uvs = [];
  37116. var diameter = options.diameter || 1;
  37117. var thickness = options.thickness || 0.5;
  37118. var tessellation = options.tessellation || 16;
  37119. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37120. var stride = tessellation + 1;
  37121. for (var i = 0; i <= tessellation; i++) {
  37122. var u = i / tessellation;
  37123. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37124. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37125. for (var j = 0; j <= tessellation; j++) {
  37126. var v = 1 - j / tessellation;
  37127. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37128. var dx = Math.cos(innerAngle);
  37129. var dy = Math.sin(innerAngle);
  37130. // Create a vertex.
  37131. var normal = new BABYLON.Vector3(dx, dy, 0);
  37132. var position = normal.scale(thickness / 2);
  37133. var textureCoordinate = new BABYLON.Vector2(u, v);
  37134. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37135. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37136. positions.push(position.x, position.y, position.z);
  37137. normals.push(normal.x, normal.y, normal.z);
  37138. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37139. // And create indices for two triangles.
  37140. var nextI = (i + 1) % stride;
  37141. var nextJ = (j + 1) % stride;
  37142. indices.push(i * stride + j);
  37143. indices.push(i * stride + nextJ);
  37144. indices.push(nextI * stride + j);
  37145. indices.push(i * stride + nextJ);
  37146. indices.push(nextI * stride + nextJ);
  37147. indices.push(nextI * stride + j);
  37148. }
  37149. }
  37150. // Sides
  37151. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37152. // Result
  37153. var vertexData = new VertexData();
  37154. vertexData.indices = indices;
  37155. vertexData.positions = positions;
  37156. vertexData.normals = normals;
  37157. vertexData.uvs = uvs;
  37158. return vertexData;
  37159. };
  37160. /**
  37161. * Creates the VertexData of the LineSystem
  37162. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37163. * - lines an array of lines, each line being an array of successive Vector3
  37164. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37165. * @returns the VertexData of the LineSystem
  37166. */
  37167. VertexData.CreateLineSystem = function (options) {
  37168. var indices = [];
  37169. var positions = [];
  37170. var lines = options.lines;
  37171. var colors = options.colors;
  37172. var vertexColors = [];
  37173. var idx = 0;
  37174. for (var l = 0; l < lines.length; l++) {
  37175. var points = lines[l];
  37176. for (var index = 0; index < points.length; index++) {
  37177. positions.push(points[index].x, points[index].y, points[index].z);
  37178. if (colors) {
  37179. var color = colors[l];
  37180. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37181. }
  37182. if (index > 0) {
  37183. indices.push(idx - 1);
  37184. indices.push(idx);
  37185. }
  37186. idx++;
  37187. }
  37188. }
  37189. var vertexData = new VertexData();
  37190. vertexData.indices = indices;
  37191. vertexData.positions = positions;
  37192. if (colors) {
  37193. vertexData.colors = vertexColors;
  37194. }
  37195. return vertexData;
  37196. };
  37197. /**
  37198. * Create the VertexData for a DashedLines
  37199. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37200. * - points an array successive Vector3
  37201. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37202. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37203. * - dashNb the intended total number of dashes, optional, default 200
  37204. * @returns the VertexData for the DashedLines
  37205. */
  37206. VertexData.CreateDashedLines = function (options) {
  37207. var dashSize = options.dashSize || 3;
  37208. var gapSize = options.gapSize || 1;
  37209. var dashNb = options.dashNb || 200;
  37210. var points = options.points;
  37211. var positions = new Array();
  37212. var indices = new Array();
  37213. var curvect = BABYLON.Vector3.Zero();
  37214. var lg = 0;
  37215. var nb = 0;
  37216. var shft = 0;
  37217. var dashshft = 0;
  37218. var curshft = 0;
  37219. var idx = 0;
  37220. var i = 0;
  37221. for (i = 0; i < points.length - 1; i++) {
  37222. points[i + 1].subtractToRef(points[i], curvect);
  37223. lg += curvect.length();
  37224. }
  37225. shft = lg / dashNb;
  37226. dashshft = dashSize * shft / (dashSize + gapSize);
  37227. for (i = 0; i < points.length - 1; i++) {
  37228. points[i + 1].subtractToRef(points[i], curvect);
  37229. nb = Math.floor(curvect.length() / shft);
  37230. curvect.normalize();
  37231. for (var j = 0; j < nb; j++) {
  37232. curshft = shft * j;
  37233. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37234. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37235. indices.push(idx, idx + 1);
  37236. idx += 2;
  37237. }
  37238. }
  37239. // Result
  37240. var vertexData = new VertexData();
  37241. vertexData.positions = positions;
  37242. vertexData.indices = indices;
  37243. return vertexData;
  37244. };
  37245. /**
  37246. * Creates the VertexData for a Ground
  37247. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37248. * - width the width (x direction) of the ground, optional, default 1
  37249. * - height the height (z direction) of the ground, optional, default 1
  37250. * - subdivisions the number of subdivisions per side, optional, default 1
  37251. * @returns the VertexData of the Ground
  37252. */
  37253. VertexData.CreateGround = function (options) {
  37254. var indices = [];
  37255. var positions = [];
  37256. var normals = [];
  37257. var uvs = [];
  37258. var row, col;
  37259. var width = options.width || 1;
  37260. var height = options.height || 1;
  37261. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37262. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37263. for (row = 0; row <= subdivisionsY; row++) {
  37264. for (col = 0; col <= subdivisionsX; col++) {
  37265. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37266. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37267. positions.push(position.x, position.y, position.z);
  37268. normals.push(normal.x, normal.y, normal.z);
  37269. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37270. }
  37271. }
  37272. for (row = 0; row < subdivisionsY; row++) {
  37273. for (col = 0; col < subdivisionsX; col++) {
  37274. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37275. indices.push(col + 1 + row * (subdivisionsX + 1));
  37276. indices.push(col + row * (subdivisionsX + 1));
  37277. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37278. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37279. indices.push(col + row * (subdivisionsX + 1));
  37280. }
  37281. }
  37282. // Result
  37283. var vertexData = new VertexData();
  37284. vertexData.indices = indices;
  37285. vertexData.positions = positions;
  37286. vertexData.normals = normals;
  37287. vertexData.uvs = uvs;
  37288. return vertexData;
  37289. };
  37290. /**
  37291. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37292. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37293. * * xmin the ground minimum X coordinate, optional, default -1
  37294. * * zmin the ground minimum Z coordinate, optional, default -1
  37295. * * xmax the ground maximum X coordinate, optional, default 1
  37296. * * zmax the ground maximum Z coordinate, optional, default 1
  37297. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37298. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37299. * @returns the VertexData of the TiledGround
  37300. */
  37301. VertexData.CreateTiledGround = function (options) {
  37302. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37303. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37304. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37305. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37306. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37307. var precision = options.precision || { w: 1, h: 1 };
  37308. var indices = new Array();
  37309. var positions = new Array();
  37310. var normals = new Array();
  37311. var uvs = new Array();
  37312. var row, col, tileRow, tileCol;
  37313. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37314. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37315. precision.w = (precision.w < 1) ? 1 : precision.w;
  37316. precision.h = (precision.h < 1) ? 1 : precision.h;
  37317. var tileSize = {
  37318. 'w': (xmax - xmin) / subdivisions.w,
  37319. 'h': (zmax - zmin) / subdivisions.h
  37320. };
  37321. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37322. // Indices
  37323. var base = positions.length / 3;
  37324. var rowLength = precision.w + 1;
  37325. for (row = 0; row < precision.h; row++) {
  37326. for (col = 0; col < precision.w; col++) {
  37327. var square = [
  37328. base + col + row * rowLength,
  37329. base + (col + 1) + row * rowLength,
  37330. base + (col + 1) + (row + 1) * rowLength,
  37331. base + col + (row + 1) * rowLength
  37332. ];
  37333. indices.push(square[1]);
  37334. indices.push(square[2]);
  37335. indices.push(square[3]);
  37336. indices.push(square[0]);
  37337. indices.push(square[1]);
  37338. indices.push(square[3]);
  37339. }
  37340. }
  37341. // Position, normals and uvs
  37342. var position = BABYLON.Vector3.Zero();
  37343. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37344. for (row = 0; row <= precision.h; row++) {
  37345. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37346. for (col = 0; col <= precision.w; col++) {
  37347. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37348. position.y = 0;
  37349. positions.push(position.x, position.y, position.z);
  37350. normals.push(normal.x, normal.y, normal.z);
  37351. uvs.push(col / precision.w, row / precision.h);
  37352. }
  37353. }
  37354. }
  37355. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37356. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37357. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37358. }
  37359. }
  37360. // Result
  37361. var vertexData = new VertexData();
  37362. vertexData.indices = indices;
  37363. vertexData.positions = positions;
  37364. vertexData.normals = normals;
  37365. vertexData.uvs = uvs;
  37366. return vertexData;
  37367. };
  37368. /**
  37369. * Creates the VertexData of the Ground designed from a heightmap
  37370. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37371. * * width the width (x direction) of the ground
  37372. * * height the height (z direction) of the ground
  37373. * * subdivisions the number of subdivisions per side
  37374. * * minHeight the minimum altitude on the ground, optional, default 0
  37375. * * maxHeight the maximum altitude on the ground, optional default 1
  37376. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37377. * * buffer the array holding the image color data
  37378. * * bufferWidth the width of image
  37379. * * bufferHeight the height of image
  37380. * @returns the VertexData of the Ground designed from a heightmap
  37381. */
  37382. VertexData.CreateGroundFromHeightMap = function (options) {
  37383. var indices = [];
  37384. var positions = [];
  37385. var normals = [];
  37386. var uvs = [];
  37387. var row, col;
  37388. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37389. // Vertices
  37390. for (row = 0; row <= options.subdivisions; row++) {
  37391. for (col = 0; col <= options.subdivisions; col++) {
  37392. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  37393. // Compute height
  37394. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37395. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37396. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37397. var r = options.buffer[pos] / 255.0;
  37398. var g = options.buffer[pos + 1] / 255.0;
  37399. var b = options.buffer[pos + 2] / 255.0;
  37400. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37401. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37402. // Add vertex
  37403. positions.push(position.x, position.y, position.z);
  37404. normals.push(0, 0, 0);
  37405. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37406. }
  37407. }
  37408. // Indices
  37409. for (row = 0; row < options.subdivisions; row++) {
  37410. for (col = 0; col < options.subdivisions; col++) {
  37411. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37412. indices.push(col + 1 + row * (options.subdivisions + 1));
  37413. indices.push(col + row * (options.subdivisions + 1));
  37414. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37415. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37416. indices.push(col + row * (options.subdivisions + 1));
  37417. }
  37418. }
  37419. // Normals
  37420. VertexData.ComputeNormals(positions, indices, normals);
  37421. // Result
  37422. var vertexData = new VertexData();
  37423. vertexData.indices = indices;
  37424. vertexData.positions = positions;
  37425. vertexData.normals = normals;
  37426. vertexData.uvs = uvs;
  37427. return vertexData;
  37428. };
  37429. /**
  37430. * Creates the VertexData for a Plane
  37431. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37432. * * size sets the width and height of the plane to the value of size, optional default 1
  37433. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37434. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37435. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37436. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37437. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37438. * @returns the VertexData of the box
  37439. */
  37440. VertexData.CreatePlane = function (options) {
  37441. var indices = [];
  37442. var positions = [];
  37443. var normals = [];
  37444. var uvs = [];
  37445. var width = options.width || options.size || 1;
  37446. var height = options.height || options.size || 1;
  37447. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37448. // Vertices
  37449. var halfWidth = width / 2.0;
  37450. var halfHeight = height / 2.0;
  37451. positions.push(-halfWidth, -halfHeight, 0);
  37452. normals.push(0, 0, -1.0);
  37453. uvs.push(0.0, 0.0);
  37454. positions.push(halfWidth, -halfHeight, 0);
  37455. normals.push(0, 0, -1.0);
  37456. uvs.push(1.0, 0.0);
  37457. positions.push(halfWidth, halfHeight, 0);
  37458. normals.push(0, 0, -1.0);
  37459. uvs.push(1.0, 1.0);
  37460. positions.push(-halfWidth, halfHeight, 0);
  37461. normals.push(0, 0, -1.0);
  37462. uvs.push(0.0, 1.0);
  37463. // Indices
  37464. indices.push(0);
  37465. indices.push(1);
  37466. indices.push(2);
  37467. indices.push(0);
  37468. indices.push(2);
  37469. indices.push(3);
  37470. // Sides
  37471. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37472. // Result
  37473. var vertexData = new VertexData();
  37474. vertexData.indices = indices;
  37475. vertexData.positions = positions;
  37476. vertexData.normals = normals;
  37477. vertexData.uvs = uvs;
  37478. return vertexData;
  37479. };
  37480. /**
  37481. * Creates the VertexData of the Disc or regular Polygon
  37482. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37483. * * radius the radius of the disc, optional default 0.5
  37484. * * tessellation the number of polygon sides, optional, default 64
  37485. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37486. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37487. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37488. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37489. * @returns the VertexData of the box
  37490. */
  37491. VertexData.CreateDisc = function (options) {
  37492. var positions = new Array();
  37493. var indices = new Array();
  37494. var normals = new Array();
  37495. var uvs = new Array();
  37496. var radius = options.radius || 0.5;
  37497. var tessellation = options.tessellation || 64;
  37498. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37499. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37500. // positions and uvs
  37501. positions.push(0, 0, 0); // disc center first
  37502. uvs.push(0.5, 0.5);
  37503. var theta = Math.PI * 2 * arc;
  37504. var step = theta / tessellation;
  37505. for (var a = 0; a < theta; a += step) {
  37506. var x = Math.cos(a);
  37507. var y = Math.sin(a);
  37508. var u = (x + 1) / 2;
  37509. var v = (1 - y) / 2;
  37510. positions.push(radius * x, radius * y, 0);
  37511. uvs.push(u, v);
  37512. }
  37513. if (arc === 1) {
  37514. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37515. uvs.push(uvs[2], uvs[3]);
  37516. }
  37517. //indices
  37518. var vertexNb = positions.length / 3;
  37519. for (var i = 1; i < vertexNb - 1; i++) {
  37520. indices.push(i + 1, 0, i);
  37521. }
  37522. // result
  37523. VertexData.ComputeNormals(positions, indices, normals);
  37524. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37525. var vertexData = new VertexData();
  37526. vertexData.indices = indices;
  37527. vertexData.positions = positions;
  37528. vertexData.normals = normals;
  37529. vertexData.uvs = uvs;
  37530. return vertexData;
  37531. };
  37532. /**
  37533. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37534. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37535. * @param polygon a mesh built from polygonTriangulation.build()
  37536. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37537. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37538. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37539. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37540. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37541. * @returns the VertexData of the Polygon
  37542. */
  37543. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37544. var faceUV = fUV || new Array(3);
  37545. var faceColors = fColors;
  37546. var colors = [];
  37547. // default face colors and UV if undefined
  37548. for (var f = 0; f < 3; f++) {
  37549. if (faceUV[f] === undefined) {
  37550. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37551. }
  37552. if (faceColors && faceColors[f] === undefined) {
  37553. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37554. }
  37555. }
  37556. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37557. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37558. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37559. var indices = polygon.getIndices();
  37560. // set face colours and textures
  37561. var idx = 0;
  37562. var face = 0;
  37563. for (var index = 0; index < normals.length; index += 3) {
  37564. //Edge Face no. 1
  37565. if (Math.abs(normals[index + 1]) < 0.001) {
  37566. face = 1;
  37567. }
  37568. //Top Face no. 0
  37569. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37570. face = 0;
  37571. }
  37572. //Bottom Face no. 2
  37573. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37574. face = 2;
  37575. }
  37576. idx = index / 3;
  37577. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37578. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37579. if (faceColors) {
  37580. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37581. }
  37582. }
  37583. // sides
  37584. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37585. // Result
  37586. var vertexData = new VertexData();
  37587. vertexData.indices = indices;
  37588. vertexData.positions = positions;
  37589. vertexData.normals = normals;
  37590. vertexData.uvs = uvs;
  37591. if (faceColors) {
  37592. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37593. vertexData.colors = totalColors;
  37594. }
  37595. return vertexData;
  37596. };
  37597. /**
  37598. * Creates the VertexData of the IcoSphere
  37599. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37600. * * radius the radius of the IcoSphere, optional default 1
  37601. * * radiusX allows stretching in the x direction, optional, default radius
  37602. * * radiusY allows stretching in the y direction, optional, default radius
  37603. * * radiusZ allows stretching in the z direction, optional, default radius
  37604. * * flat when true creates a flat shaded mesh, optional, default true
  37605. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37606. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37607. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37608. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37609. * @returns the VertexData of the IcoSphere
  37610. */
  37611. VertexData.CreateIcoSphere = function (options) {
  37612. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37613. var radius = options.radius || 1;
  37614. var flat = (options.flat === undefined) ? true : options.flat;
  37615. var subdivisions = options.subdivisions || 4;
  37616. var radiusX = options.radiusX || radius;
  37617. var radiusY = options.radiusY || radius;
  37618. var radiusZ = options.radiusZ || radius;
  37619. var t = (1 + Math.sqrt(5)) / 2;
  37620. // 12 vertex x,y,z
  37621. var ico_vertices = [
  37622. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37623. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37624. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37625. ];
  37626. // index of 3 vertex makes a face of icopshere
  37627. var ico_indices = [
  37628. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37629. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37630. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37631. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37632. ];
  37633. // vertex for uv have aliased position, not for UV
  37634. var vertices_unalias_id = [
  37635. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37636. // vertex alias
  37637. 0,
  37638. 2,
  37639. 3,
  37640. 3,
  37641. 3,
  37642. 4,
  37643. 7,
  37644. 8,
  37645. 9,
  37646. 9,
  37647. 10,
  37648. 11 // 23: B + 12
  37649. ];
  37650. // uv as integer step (not pixels !)
  37651. var ico_vertexuv = [
  37652. 5, 1, 3, 1, 6, 4, 0, 0,
  37653. 5, 3, 4, 2, 2, 2, 4, 0,
  37654. 2, 0, 1, 1, 6, 0, 6, 2,
  37655. // vertex alias (for same vertex on different faces)
  37656. 0, 4,
  37657. 3, 3,
  37658. 4, 4,
  37659. 3, 1,
  37660. 4, 2,
  37661. 4, 4,
  37662. 0, 2,
  37663. 1, 1,
  37664. 2, 2,
  37665. 3, 3,
  37666. 1, 3,
  37667. 2, 4 // 23: B + 12
  37668. ];
  37669. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37670. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37671. // First island of uv mapping
  37672. // v = 4h 3+ 2
  37673. // v = 3h 9+ 4
  37674. // v = 2h 9+ 5 B
  37675. // v = 1h 9 1 0
  37676. // v = 0h 3 8 7 A
  37677. // u = 0 1 2 3 4 5 6 *a
  37678. // Second island of uv mapping
  37679. // v = 4h 0+ B+ 4+
  37680. // v = 3h A+ 2+
  37681. // v = 2h 7+ 6 3+
  37682. // v = 1h 8+ 3+
  37683. // v = 0h
  37684. // u = 0 1 2 3 4 5 6 *a
  37685. // Face layout on texture UV mapping
  37686. // ============
  37687. // \ 4 /\ 16 / ======
  37688. // \ / \ / /\ 11 /
  37689. // \/ 7 \/ / \ /
  37690. // ======= / 10 \/
  37691. // /\ 17 /\ =======
  37692. // / \ / \ \ 15 /\
  37693. // / 8 \/ 12 \ \ / \
  37694. // ============ \/ 6 \
  37695. // \ 18 /\ ============
  37696. // \ / \ \ 5 /\ 0 /
  37697. // \/ 13 \ \ / \ /
  37698. // ======= \/ 1 \/
  37699. // =============
  37700. // /\ 19 /\ 2 /\
  37701. // / \ / \ / \
  37702. // / 14 \/ 9 \/ 3 \
  37703. // ===================
  37704. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37705. var ustep = 138 / 1024;
  37706. var vstep = 239 / 1024;
  37707. var uoffset = 60 / 1024;
  37708. var voffset = 26 / 1024;
  37709. // Second island should have margin, not to touch the first island
  37710. // avoid any borderline artefact in pixel rounding
  37711. var island_u_offset = -40 / 1024;
  37712. var island_v_offset = +20 / 1024;
  37713. // face is either island 0 or 1 :
  37714. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37715. var island = [
  37716. 0, 0, 0, 0, 1,
  37717. 0, 0, 1, 1, 0,
  37718. 0, 0, 1, 1, 0,
  37719. 0, 1, 1, 1, 0 // 15 - 19
  37720. ];
  37721. var indices = new Array();
  37722. var positions = new Array();
  37723. var normals = new Array();
  37724. var uvs = new Array();
  37725. var current_indice = 0;
  37726. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37727. var face_vertex_pos = new Array(3);
  37728. var face_vertex_uv = new Array(3);
  37729. var v012;
  37730. for (v012 = 0; v012 < 3; v012++) {
  37731. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37732. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37733. }
  37734. // create all with normals
  37735. for (var face = 0; face < 20; face++) {
  37736. // 3 vertex per face
  37737. for (v012 = 0; v012 < 3; v012++) {
  37738. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37739. var v_id = ico_indices[3 * face + v012];
  37740. // vertex have 3D position (x,y,z)
  37741. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  37742. // Normalize to get normal, then scale to radius
  37743. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37744. // uv Coordinates from vertex ID
  37745. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  37746. }
  37747. // Subdivide the face (interpolate pos, norm, uv)
  37748. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37749. // - norm is linear interpolation of vertex corner normal
  37750. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37751. // - uv is linear interpolation
  37752. //
  37753. // Topology is as below for sub-divide by 2
  37754. // vertex shown as v0,v1,v2
  37755. // interp index is i1 to progress in range [v0,v1[
  37756. // interp index is i2 to progress in range [v0,v2[
  37757. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37758. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37759. //
  37760. //
  37761. // i2 v2
  37762. // ^ ^
  37763. // / / \
  37764. // / / \
  37765. // / / \
  37766. // / / (0,1) \
  37767. // / #---------\
  37768. // / / \ (0,0)'/ \
  37769. // / / \ / \
  37770. // / / \ / \
  37771. // / / (0,0) \ / (1,0) \
  37772. // / #---------#---------\
  37773. // v0 v1
  37774. //
  37775. // --------------------> i1
  37776. //
  37777. // interp of (i1,i2):
  37778. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37779. // along i1 : lerp(x0,x1, i1/(S-i2))
  37780. //
  37781. // centroid of triangle is needed to get help normal computation
  37782. // (c1,c2) are used for centroid location
  37783. var interp_vertex = function (i1, i2, c1, c2) {
  37784. // vertex is interpolated from
  37785. // - face_vertex_pos[0..2]
  37786. // - face_vertex_uv[0..2]
  37787. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37788. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37789. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37790. pos_interp.normalize();
  37791. var vertex_normal;
  37792. if (flat) {
  37793. // in flat mode, recalculate normal as face centroid normal
  37794. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37795. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37796. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37797. }
  37798. else {
  37799. // in smooth mode, recalculate normal from each single vertex position
  37800. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37801. }
  37802. // Vertex normal need correction due to X,Y,Z radius scaling
  37803. vertex_normal.x /= radiusX;
  37804. vertex_normal.y /= radiusY;
  37805. vertex_normal.z /= radiusZ;
  37806. vertex_normal.normalize();
  37807. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37808. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37809. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37810. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37811. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37812. uvs.push(uv_interp.x, uv_interp.y);
  37813. // push each vertex has member of a face
  37814. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37815. indices.push(current_indice);
  37816. current_indice++;
  37817. };
  37818. for (var i2 = 0; i2 < subdivisions; i2++) {
  37819. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37820. // face : (i1,i2) for /\ :
  37821. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37822. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37823. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37824. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37825. if (i1 + i2 + 1 < subdivisions) {
  37826. // face : (i1,i2)' for \/ :
  37827. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37828. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37829. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37830. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37831. }
  37832. }
  37833. }
  37834. }
  37835. // Sides
  37836. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37837. // Result
  37838. var vertexData = new VertexData();
  37839. vertexData.indices = indices;
  37840. vertexData.positions = positions;
  37841. vertexData.normals = normals;
  37842. vertexData.uvs = uvs;
  37843. return vertexData;
  37844. };
  37845. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37846. /**
  37847. * Creates the VertexData for a Polyhedron
  37848. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37849. * * type provided types are:
  37850. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37851. * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  37852. * * size the size of the IcoSphere, optional default 1
  37853. * * sizeX allows stretching in the x direction, optional, default size
  37854. * * sizeY allows stretching in the y direction, optional, default size
  37855. * * sizeZ allows stretching in the z direction, optional, default size
  37856. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  37857. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37858. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37859. * * flat when true creates a flat shaded mesh, optional, default true
  37860. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37861. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37862. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37863. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37864. * @returns the VertexData of the Polyhedron
  37865. */
  37866. VertexData.CreatePolyhedron = function (options) {
  37867. // provided polyhedron types :
  37868. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37869. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  37870. var polyhedra = [];
  37871. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  37872. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  37873. polyhedra[2] = {
  37874. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  37875. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  37876. };
  37877. polyhedra[3] = {
  37878. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  37879. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  37880. };
  37881. polyhedra[4] = {
  37882. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  37883. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  37884. };
  37885. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  37886. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  37887. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  37888. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  37889. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  37890. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  37891. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  37892. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  37893. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  37894. polyhedra[14] = {
  37895. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  37896. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  37897. };
  37898. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37899. var size = options.size;
  37900. var sizeX = options.sizeX || size || 1;
  37901. var sizeY = options.sizeY || size || 1;
  37902. var sizeZ = options.sizeZ || size || 1;
  37903. var data = options.custom || polyhedra[type];
  37904. var nbfaces = data.face.length;
  37905. var faceUV = options.faceUV || new Array(nbfaces);
  37906. var faceColors = options.faceColors;
  37907. var flat = (options.flat === undefined) ? true : options.flat;
  37908. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37909. var positions = new Array();
  37910. var indices = new Array();
  37911. var normals = new Array();
  37912. var uvs = new Array();
  37913. var colors = new Array();
  37914. var index = 0;
  37915. var faceIdx = 0; // face cursor in the array "indexes"
  37916. var indexes = new Array();
  37917. var i = 0;
  37918. var f = 0;
  37919. var u, v, ang, x, y, tmp;
  37920. // default face colors and UV if undefined
  37921. if (flat) {
  37922. for (f = 0; f < nbfaces; f++) {
  37923. if (faceColors && faceColors[f] === undefined) {
  37924. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37925. }
  37926. if (faceUV && faceUV[f] === undefined) {
  37927. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37928. }
  37929. }
  37930. }
  37931. if (!flat) {
  37932. for (i = 0; i < data.vertex.length; i++) {
  37933. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37934. uvs.push(0, 0);
  37935. }
  37936. for (f = 0; f < nbfaces; f++) {
  37937. for (i = 0; i < data.face[f].length - 2; i++) {
  37938. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37939. }
  37940. }
  37941. }
  37942. else {
  37943. for (f = 0; f < nbfaces; f++) {
  37944. var fl = data.face[f].length; // number of vertices of the current face
  37945. ang = 2 * Math.PI / fl;
  37946. x = 0.5 * Math.tan(ang / 2);
  37947. y = 0.5;
  37948. // positions, uvs, colors
  37949. for (i = 0; i < fl; i++) {
  37950. // positions
  37951. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  37952. indexes.push(index);
  37953. index++;
  37954. // uvs
  37955. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37956. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37957. uvs.push(u, v);
  37958. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37959. y = x * Math.sin(ang) + y * Math.cos(ang);
  37960. x = tmp;
  37961. // colors
  37962. if (faceColors) {
  37963. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37964. }
  37965. }
  37966. // indices from indexes
  37967. for (i = 0; i < fl - 2; i++) {
  37968. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37969. }
  37970. faceIdx += fl;
  37971. }
  37972. }
  37973. VertexData.ComputeNormals(positions, indices, normals);
  37974. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37975. var vertexData = new VertexData();
  37976. vertexData.positions = positions;
  37977. vertexData.indices = indices;
  37978. vertexData.normals = normals;
  37979. vertexData.uvs = uvs;
  37980. if (faceColors && flat) {
  37981. vertexData.colors = colors;
  37982. }
  37983. return vertexData;
  37984. };
  37985. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37986. /**
  37987. * Creates the VertexData for a TorusKnot
  37988. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37989. * * radius the radius of the torus knot, optional, default 2
  37990. * * tube the thickness of the tube, optional, default 0.5
  37991. * * radialSegments the number of sides on each tube segments, optional, default 32
  37992. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37993. * * p the number of windings around the z axis, optional, default 2
  37994. * * q the number of windings around the x axis, optional, default 3
  37995. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37996. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37997. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37998. * @returns the VertexData of the Torus Knot
  37999. */
  38000. VertexData.CreateTorusKnot = function (options) {
  38001. var indices = new Array();
  38002. var positions = new Array();
  38003. var normals = new Array();
  38004. var uvs = new Array();
  38005. var radius = options.radius || 2;
  38006. var tube = options.tube || 0.5;
  38007. var radialSegments = options.radialSegments || 32;
  38008. var tubularSegments = options.tubularSegments || 32;
  38009. var p = options.p || 2;
  38010. var q = options.q || 3;
  38011. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38012. // Helper
  38013. var getPos = function (angle) {
  38014. var cu = Math.cos(angle);
  38015. var su = Math.sin(angle);
  38016. var quOverP = q / p * angle;
  38017. var cs = Math.cos(quOverP);
  38018. var tx = radius * (2 + cs) * 0.5 * cu;
  38019. var ty = radius * (2 + cs) * su * 0.5;
  38020. var tz = radius * Math.sin(quOverP) * 0.5;
  38021. return new BABYLON.Vector3(tx, ty, tz);
  38022. };
  38023. // Vertices
  38024. var i;
  38025. var j;
  38026. for (i = 0; i <= radialSegments; i++) {
  38027. var modI = i % radialSegments;
  38028. var u = modI / radialSegments * 2 * p * Math.PI;
  38029. var p1 = getPos(u);
  38030. var p2 = getPos(u + 0.01);
  38031. var tang = p2.subtract(p1);
  38032. var n = p2.add(p1);
  38033. var bitan = BABYLON.Vector3.Cross(tang, n);
  38034. n = BABYLON.Vector3.Cross(bitan, tang);
  38035. bitan.normalize();
  38036. n.normalize();
  38037. for (j = 0; j < tubularSegments; j++) {
  38038. var modJ = j % tubularSegments;
  38039. var v = modJ / tubularSegments * 2 * Math.PI;
  38040. var cx = -tube * Math.cos(v);
  38041. var cy = tube * Math.sin(v);
  38042. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38043. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38044. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38045. uvs.push(i / radialSegments);
  38046. uvs.push(j / tubularSegments);
  38047. }
  38048. }
  38049. for (i = 0; i < radialSegments; i++) {
  38050. for (j = 0; j < tubularSegments; j++) {
  38051. var jNext = (j + 1) % tubularSegments;
  38052. var a = i * tubularSegments + j;
  38053. var b = (i + 1) * tubularSegments + j;
  38054. var c = (i + 1) * tubularSegments + jNext;
  38055. var d = i * tubularSegments + jNext;
  38056. indices.push(d);
  38057. indices.push(b);
  38058. indices.push(a);
  38059. indices.push(d);
  38060. indices.push(c);
  38061. indices.push(b);
  38062. }
  38063. }
  38064. // Normals
  38065. VertexData.ComputeNormals(positions, indices, normals);
  38066. // Sides
  38067. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38068. // Result
  38069. var vertexData = new VertexData();
  38070. vertexData.indices = indices;
  38071. vertexData.positions = positions;
  38072. vertexData.normals = normals;
  38073. vertexData.uvs = uvs;
  38074. return vertexData;
  38075. };
  38076. // Tools
  38077. /**
  38078. * Compute normals for given positions and indices
  38079. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38080. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38081. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38082. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38083. * * facetNormals : optional array of facet normals (vector3)
  38084. * * facetPositions : optional array of facet positions (vector3)
  38085. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38086. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38087. * * bInfo : optional bounding info, required for facetPartitioning computation
  38088. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38089. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38090. * * useRightHandedSystem: optional boolean to for right handed system computation
  38091. * * depthSort : optional boolean to enable the facet depth sort computation
  38092. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38093. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38094. */
  38095. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38096. // temporary scalar variables
  38097. var index = 0; // facet index
  38098. var p1p2x = 0.0; // p1p2 vector x coordinate
  38099. var p1p2y = 0.0; // p1p2 vector y coordinate
  38100. var p1p2z = 0.0; // p1p2 vector z coordinate
  38101. var p3p2x = 0.0; // p3p2 vector x coordinate
  38102. var p3p2y = 0.0; // p3p2 vector y coordinate
  38103. var p3p2z = 0.0; // p3p2 vector z coordinate
  38104. var faceNormalx = 0.0; // facet normal x coordinate
  38105. var faceNormaly = 0.0; // facet normal y coordinate
  38106. var faceNormalz = 0.0; // facet normal z coordinate
  38107. var length = 0.0; // facet normal length before normalization
  38108. var v1x = 0; // vector1 x index in the positions array
  38109. var v1y = 0; // vector1 y index in the positions array
  38110. var v1z = 0; // vector1 z index in the positions array
  38111. var v2x = 0; // vector2 x index in the positions array
  38112. var v2y = 0; // vector2 y index in the positions array
  38113. var v2z = 0; // vector2 z index in the positions array
  38114. var v3x = 0; // vector3 x index in the positions array
  38115. var v3y = 0; // vector3 y index in the positions array
  38116. var v3z = 0; // vector3 z index in the positions array
  38117. var computeFacetNormals = false;
  38118. var computeFacetPositions = false;
  38119. var computeFacetPartitioning = false;
  38120. var computeDepthSort = false;
  38121. var faceNormalSign = 1;
  38122. var ratio = 0;
  38123. var distanceTo = null;
  38124. if (options) {
  38125. computeFacetNormals = (options.facetNormals) ? true : false;
  38126. computeFacetPositions = (options.facetPositions) ? true : false;
  38127. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38128. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38129. ratio = options.ratio || 0;
  38130. computeDepthSort = (options.depthSort) ? true : false;
  38131. distanceTo = (options.distanceTo);
  38132. if (computeDepthSort) {
  38133. if (distanceTo === undefined) {
  38134. distanceTo = BABYLON.Vector3.Zero();
  38135. }
  38136. var depthSortedFacets = options.depthSortedFacets;
  38137. }
  38138. }
  38139. // facetPartitioning reinit if needed
  38140. var xSubRatio = 0;
  38141. var ySubRatio = 0;
  38142. var zSubRatio = 0;
  38143. var subSq = 0;
  38144. if (computeFacetPartitioning && options && options.bbSize) {
  38145. var ox = 0; // X partitioning index for facet position
  38146. var oy = 0; // Y partinioning index for facet position
  38147. var oz = 0; // Z partinioning index for facet position
  38148. var b1x = 0; // X partitioning index for facet v1 vertex
  38149. var b1y = 0; // Y partitioning index for facet v1 vertex
  38150. var b1z = 0; // z partitioning index for facet v1 vertex
  38151. var b2x = 0; // X partitioning index for facet v2 vertex
  38152. var b2y = 0; // Y partitioning index for facet v2 vertex
  38153. var b2z = 0; // Z partitioning index for facet v2 vertex
  38154. var b3x = 0; // X partitioning index for facet v3 vertex
  38155. var b3y = 0; // Y partitioning index for facet v3 vertex
  38156. var b3z = 0; // Z partitioning index for facet v3 vertex
  38157. var block_idx_o = 0; // facet barycenter block index
  38158. var block_idx_v1 = 0; // v1 vertex block index
  38159. var block_idx_v2 = 0; // v2 vertex block index
  38160. var block_idx_v3 = 0; // v3 vertex block index
  38161. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38162. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38163. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38164. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38165. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38166. subSq = options.subDiv.max * options.subDiv.max;
  38167. options.facetPartitioning.length = 0;
  38168. }
  38169. // reset the normals
  38170. for (index = 0; index < positions.length; index++) {
  38171. normals[index] = 0.0;
  38172. }
  38173. // Loop : 1 indice triplet = 1 facet
  38174. var nbFaces = (indices.length / 3) | 0;
  38175. for (index = 0; index < nbFaces; index++) {
  38176. // get the indexes of the coordinates of each vertex of the facet
  38177. v1x = indices[index * 3] * 3;
  38178. v1y = v1x + 1;
  38179. v1z = v1x + 2;
  38180. v2x = indices[index * 3 + 1] * 3;
  38181. v2y = v2x + 1;
  38182. v2z = v2x + 2;
  38183. v3x = indices[index * 3 + 2] * 3;
  38184. v3y = v3x + 1;
  38185. v3z = v3x + 2;
  38186. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38187. p1p2y = positions[v1y] - positions[v2y];
  38188. p1p2z = positions[v1z] - positions[v2z];
  38189. p3p2x = positions[v3x] - positions[v2x];
  38190. p3p2y = positions[v3y] - positions[v2y];
  38191. p3p2z = positions[v3z] - positions[v2z];
  38192. // compute the face normal with the cross product
  38193. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38194. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38195. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38196. // normalize this normal and store it in the array facetData
  38197. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38198. length = (length === 0) ? 1.0 : length;
  38199. faceNormalx /= length;
  38200. faceNormaly /= length;
  38201. faceNormalz /= length;
  38202. if (computeFacetNormals && options) {
  38203. options.facetNormals[index].x = faceNormalx;
  38204. options.facetNormals[index].y = faceNormaly;
  38205. options.facetNormals[index].z = faceNormalz;
  38206. }
  38207. if (computeFacetPositions && options) {
  38208. // compute and the facet barycenter coordinates in the array facetPositions
  38209. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38210. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38211. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38212. }
  38213. if (computeFacetPartitioning && options) {
  38214. // store the facet indexes in arrays in the main facetPartitioning array :
  38215. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38216. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38217. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38218. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38219. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38220. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38221. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38222. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38223. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38224. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38225. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38226. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38227. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38228. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38229. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38230. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38231. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38232. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38233. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38234. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38235. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38236. // push each facet index in each block containing the vertex
  38237. options.facetPartitioning[block_idx_v1].push(index);
  38238. if (block_idx_v2 != block_idx_v1) {
  38239. options.facetPartitioning[block_idx_v2].push(index);
  38240. }
  38241. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38242. options.facetPartitioning[block_idx_v3].push(index);
  38243. }
  38244. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38245. options.facetPartitioning[block_idx_o].push(index);
  38246. }
  38247. }
  38248. if (computeDepthSort && options && options.facetPositions) {
  38249. var dsf = depthSortedFacets[index];
  38250. dsf.ind = index * 3;
  38251. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38252. }
  38253. // compute the normals anyway
  38254. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38255. normals[v1y] += faceNormaly;
  38256. normals[v1z] += faceNormalz;
  38257. normals[v2x] += faceNormalx;
  38258. normals[v2y] += faceNormaly;
  38259. normals[v2z] += faceNormalz;
  38260. normals[v3x] += faceNormalx;
  38261. normals[v3y] += faceNormaly;
  38262. normals[v3z] += faceNormalz;
  38263. }
  38264. // last normalization of each normal
  38265. for (index = 0; index < normals.length / 3; index++) {
  38266. faceNormalx = normals[index * 3];
  38267. faceNormaly = normals[index * 3 + 1];
  38268. faceNormalz = normals[index * 3 + 2];
  38269. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38270. length = (length === 0) ? 1.0 : length;
  38271. faceNormalx /= length;
  38272. faceNormaly /= length;
  38273. faceNormalz /= length;
  38274. normals[index * 3] = faceNormalx;
  38275. normals[index * 3 + 1] = faceNormaly;
  38276. normals[index * 3 + 2] = faceNormalz;
  38277. }
  38278. };
  38279. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38280. var li = indices.length;
  38281. var ln = normals.length;
  38282. var i;
  38283. var n;
  38284. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38285. switch (sideOrientation) {
  38286. case BABYLON.Mesh.FRONTSIDE:
  38287. // nothing changed
  38288. break;
  38289. case BABYLON.Mesh.BACKSIDE:
  38290. var tmp;
  38291. // indices
  38292. for (i = 0; i < li; i += 3) {
  38293. tmp = indices[i];
  38294. indices[i] = indices[i + 2];
  38295. indices[i + 2] = tmp;
  38296. }
  38297. // normals
  38298. for (n = 0; n < ln; n++) {
  38299. normals[n] = -normals[n];
  38300. }
  38301. break;
  38302. case BABYLON.Mesh.DOUBLESIDE:
  38303. // positions
  38304. var lp = positions.length;
  38305. var l = lp / 3;
  38306. for (var p = 0; p < lp; p++) {
  38307. positions[lp + p] = positions[p];
  38308. }
  38309. // indices
  38310. for (i = 0; i < li; i += 3) {
  38311. indices[i + li] = indices[i + 2] + l;
  38312. indices[i + 1 + li] = indices[i + 1] + l;
  38313. indices[i + 2 + li] = indices[i] + l;
  38314. }
  38315. // normals
  38316. for (n = 0; n < ln; n++) {
  38317. normals[ln + n] = -normals[n];
  38318. }
  38319. // uvs
  38320. var lu = uvs.length;
  38321. var u = 0;
  38322. for (u = 0; u < lu; u++) {
  38323. uvs[u + lu] = uvs[u];
  38324. }
  38325. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38326. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38327. u = 0;
  38328. for (i = 0; i < lu / 2; i++) {
  38329. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38330. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38331. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38332. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38333. u += 2;
  38334. }
  38335. break;
  38336. }
  38337. };
  38338. /**
  38339. * Applies VertexData created from the imported parameters to the geometry
  38340. * @param parsedVertexData the parsed data from an imported file
  38341. * @param geometry the geometry to apply the VertexData to
  38342. */
  38343. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38344. var vertexData = new VertexData();
  38345. // positions
  38346. var positions = parsedVertexData.positions;
  38347. if (positions) {
  38348. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38349. }
  38350. // normals
  38351. var normals = parsedVertexData.normals;
  38352. if (normals) {
  38353. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38354. }
  38355. // tangents
  38356. var tangents = parsedVertexData.tangents;
  38357. if (tangents) {
  38358. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38359. }
  38360. // uvs
  38361. var uvs = parsedVertexData.uvs;
  38362. if (uvs) {
  38363. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38364. }
  38365. // uv2s
  38366. var uv2s = parsedVertexData.uv2s;
  38367. if (uv2s) {
  38368. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38369. }
  38370. // uv3s
  38371. var uv3s = parsedVertexData.uv3s;
  38372. if (uv3s) {
  38373. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38374. }
  38375. // uv4s
  38376. var uv4s = parsedVertexData.uv4s;
  38377. if (uv4s) {
  38378. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38379. }
  38380. // uv5s
  38381. var uv5s = parsedVertexData.uv5s;
  38382. if (uv5s) {
  38383. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38384. }
  38385. // uv6s
  38386. var uv6s = parsedVertexData.uv6s;
  38387. if (uv6s) {
  38388. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38389. }
  38390. // colors
  38391. var colors = parsedVertexData.colors;
  38392. if (colors) {
  38393. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38394. }
  38395. // matricesIndices
  38396. var matricesIndices = parsedVertexData.matricesIndices;
  38397. if (matricesIndices) {
  38398. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38399. }
  38400. // matricesWeights
  38401. var matricesWeights = parsedVertexData.matricesWeights;
  38402. if (matricesWeights) {
  38403. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38404. }
  38405. // indices
  38406. var indices = parsedVertexData.indices;
  38407. if (indices) {
  38408. vertexData.indices = indices;
  38409. }
  38410. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38411. };
  38412. return VertexData;
  38413. }());
  38414. BABYLON.VertexData = VertexData;
  38415. })(BABYLON || (BABYLON = {}));
  38416. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38417. var BABYLON;
  38418. (function (BABYLON) {
  38419. /**
  38420. * Class used to store geometry data (vertex buffers + index buffer)
  38421. */
  38422. var Geometry = /** @class */ (function () {
  38423. /**
  38424. * Creates a new geometry
  38425. * @param id defines the unique ID
  38426. * @param scene defines the hosting scene
  38427. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38428. * @param updatable defines if geometry must be updatable (false by default)
  38429. * @param mesh defines the mesh that will be associated with the geometry
  38430. */
  38431. function Geometry(id, scene, vertexData, updatable, mesh) {
  38432. if (updatable === void 0) { updatable = false; }
  38433. if (mesh === void 0) { mesh = null; }
  38434. /**
  38435. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38436. */
  38437. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38438. this._totalVertices = 0;
  38439. this._isDisposed = false;
  38440. this._indexBufferIsUpdatable = false;
  38441. this.id = id;
  38442. this._engine = scene.getEngine();
  38443. this._meshes = [];
  38444. this._scene = scene;
  38445. //Init vertex buffer cache
  38446. this._vertexBuffers = {};
  38447. this._indices = [];
  38448. this._updatable = updatable;
  38449. // vertexData
  38450. if (vertexData) {
  38451. this.setAllVerticesData(vertexData, updatable);
  38452. }
  38453. else {
  38454. this._totalVertices = 0;
  38455. this._indices = [];
  38456. }
  38457. if (this._engine.getCaps().vertexArrayObject) {
  38458. this._vertexArrayObjects = {};
  38459. }
  38460. // applyToMesh
  38461. if (mesh) {
  38462. if (mesh.getClassName() === "LinesMesh") {
  38463. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38464. this._updateExtend();
  38465. }
  38466. this.applyToMesh(mesh);
  38467. mesh.computeWorldMatrix(true);
  38468. }
  38469. }
  38470. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38471. /**
  38472. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  38473. */
  38474. get: function () {
  38475. return this._boundingBias;
  38476. },
  38477. /**
  38478. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  38479. */
  38480. set: function (value) {
  38481. if (this._boundingBias && this._boundingBias.equals(value)) {
  38482. return;
  38483. }
  38484. this._boundingBias = value.clone();
  38485. this._updateBoundingInfo(true, null);
  38486. },
  38487. enumerable: true,
  38488. configurable: true
  38489. });
  38490. /**
  38491. * Static function used to attach a new empty geometry to a mesh
  38492. * @param mesh defines the mesh to attach the geometry to
  38493. * @returns the new {BABYLON.Geometry}
  38494. */
  38495. Geometry.CreateGeometryForMesh = function (mesh) {
  38496. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38497. geometry.applyToMesh(mesh);
  38498. return geometry;
  38499. };
  38500. Object.defineProperty(Geometry.prototype, "extend", {
  38501. /**
  38502. * Gets the current extend of the geometry
  38503. */
  38504. get: function () {
  38505. return this._extend;
  38506. },
  38507. enumerable: true,
  38508. configurable: true
  38509. });
  38510. /**
  38511. * Gets the hosting scene
  38512. * @returns the hosting {BABYLON.Scene}
  38513. */
  38514. Geometry.prototype.getScene = function () {
  38515. return this._scene;
  38516. };
  38517. /**
  38518. * Gets the hosting engine
  38519. * @returns the hosting {BABYLON.Engine}
  38520. */
  38521. Geometry.prototype.getEngine = function () {
  38522. return this._engine;
  38523. };
  38524. /**
  38525. * Defines if the geometry is ready to use
  38526. * @returns true if the geometry is ready to be used
  38527. */
  38528. Geometry.prototype.isReady = function () {
  38529. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38530. };
  38531. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38532. /**
  38533. * Gets a value indicating that the geometry should not be serialized
  38534. */
  38535. get: function () {
  38536. for (var index = 0; index < this._meshes.length; index++) {
  38537. if (!this._meshes[index].doNotSerialize) {
  38538. return false;
  38539. }
  38540. }
  38541. return true;
  38542. },
  38543. enumerable: true,
  38544. configurable: true
  38545. });
  38546. /** @hidden */
  38547. Geometry.prototype._rebuild = function () {
  38548. if (this._vertexArrayObjects) {
  38549. this._vertexArrayObjects = {};
  38550. }
  38551. // Index buffer
  38552. if (this._meshes.length !== 0 && this._indices) {
  38553. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38554. }
  38555. // Vertex buffers
  38556. for (var key in this._vertexBuffers) {
  38557. var vertexBuffer = this._vertexBuffers[key];
  38558. vertexBuffer._rebuild();
  38559. }
  38560. };
  38561. /**
  38562. * Affects all geometry data in one call
  38563. * @param vertexData defines the geometry data
  38564. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38565. */
  38566. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38567. vertexData.applyToGeometry(this, updatable);
  38568. this.notifyUpdate();
  38569. };
  38570. /**
  38571. * Set specific vertex data
  38572. * @param kind defines the data kind (Position, normal, etc...)
  38573. * @param data defines the vertex data to use
  38574. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38575. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38576. */
  38577. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38578. if (updatable === void 0) { updatable = false; }
  38579. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38580. this.setVerticesBuffer(buffer);
  38581. };
  38582. /**
  38583. * Removes a specific vertex data
  38584. * @param kind defines the data kind (Position, normal, etc...)
  38585. */
  38586. Geometry.prototype.removeVerticesData = function (kind) {
  38587. if (this._vertexBuffers[kind]) {
  38588. this._vertexBuffers[kind].dispose();
  38589. delete this._vertexBuffers[kind];
  38590. }
  38591. };
  38592. /**
  38593. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38594. * @param buffer defines the vertex buffer to use
  38595. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38596. */
  38597. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38598. if (totalVertices === void 0) { totalVertices = null; }
  38599. var kind = buffer.getKind();
  38600. if (this._vertexBuffers[kind]) {
  38601. this._vertexBuffers[kind].dispose();
  38602. }
  38603. this._vertexBuffers[kind] = buffer;
  38604. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38605. var data = buffer.getData();
  38606. if (totalVertices != null) {
  38607. this._totalVertices = totalVertices;
  38608. }
  38609. else {
  38610. if (data != null) {
  38611. this._totalVertices = data.length / (buffer.byteStride / 4);
  38612. }
  38613. }
  38614. this._updateExtend(data);
  38615. this._resetPointsArrayCache();
  38616. var meshes = this._meshes;
  38617. var numOfMeshes = meshes.length;
  38618. for (var index = 0; index < numOfMeshes; index++) {
  38619. var mesh = meshes[index];
  38620. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38621. mesh._createGlobalSubMesh(false);
  38622. mesh.computeWorldMatrix(true);
  38623. }
  38624. }
  38625. this.notifyUpdate(kind);
  38626. if (this._vertexArrayObjects) {
  38627. this._disposeVertexArrayObjects();
  38628. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38629. }
  38630. };
  38631. /**
  38632. * Update a specific vertex buffer
  38633. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38634. * It will do nothing if the buffer is not updatable
  38635. * @param kind defines the data kind (Position, normal, etc...)
  38636. * @param data defines the data to use
  38637. * @param offset defines the offset in the target buffer where to store the data
  38638. * @param useBytes set to true if the offset is in bytes
  38639. */
  38640. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38641. if (useBytes === void 0) { useBytes = false; }
  38642. var vertexBuffer = this.getVertexBuffer(kind);
  38643. if (!vertexBuffer) {
  38644. return;
  38645. }
  38646. vertexBuffer.updateDirectly(data, offset, useBytes);
  38647. this.notifyUpdate(kind);
  38648. };
  38649. /**
  38650. * Update a specific vertex buffer
  38651. * This function will create a new buffer if the current one is not updatable
  38652. * @param kind defines the data kind (Position, normal, etc...)
  38653. * @param data defines the data to use
  38654. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38655. */
  38656. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38657. if (updateExtends === void 0) { updateExtends = false; }
  38658. var vertexBuffer = this.getVertexBuffer(kind);
  38659. if (!vertexBuffer) {
  38660. return;
  38661. }
  38662. vertexBuffer.update(data);
  38663. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38664. this._updateBoundingInfo(updateExtends, data);
  38665. }
  38666. this.notifyUpdate(kind);
  38667. };
  38668. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38669. if (updateExtends) {
  38670. this._updateExtend(data);
  38671. }
  38672. var meshes = this._meshes;
  38673. var numOfMeshes = meshes.length;
  38674. this._resetPointsArrayCache();
  38675. for (var index = 0; index < numOfMeshes; index++) {
  38676. var mesh = meshes[index];
  38677. if (updateExtends) {
  38678. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38679. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38680. var subMesh = mesh.subMeshes[subIndex];
  38681. subMesh.refreshBoundingInfo();
  38682. }
  38683. }
  38684. }
  38685. };
  38686. /** @hidden */
  38687. Geometry.prototype._bind = function (effect, indexToBind) {
  38688. if (!effect) {
  38689. return;
  38690. }
  38691. if (indexToBind === undefined) {
  38692. indexToBind = this._indexBuffer;
  38693. }
  38694. var vbs = this.getVertexBuffers();
  38695. if (!vbs) {
  38696. return;
  38697. }
  38698. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38699. this._engine.bindBuffers(vbs, indexToBind, effect);
  38700. return;
  38701. }
  38702. // Using VAO
  38703. if (!this._vertexArrayObjects[effect.key]) {
  38704. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38705. }
  38706. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38707. };
  38708. /**
  38709. * Gets total number of vertices
  38710. * @returns the total number of vertices
  38711. */
  38712. Geometry.prototype.getTotalVertices = function () {
  38713. if (!this.isReady()) {
  38714. return 0;
  38715. }
  38716. return this._totalVertices;
  38717. };
  38718. /**
  38719. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38720. * @param kind defines the data kind (Position, normal, etc...)
  38721. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38722. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38723. * @returns a float array containing vertex data
  38724. */
  38725. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38726. var vertexBuffer = this.getVertexBuffer(kind);
  38727. if (!vertexBuffer) {
  38728. return null;
  38729. }
  38730. var data = vertexBuffer.getData();
  38731. if (!data) {
  38732. return null;
  38733. }
  38734. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38735. var count = this._totalVertices * vertexBuffer.getSize();
  38736. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38737. var copy_1 = new Array(count);
  38738. vertexBuffer.forEach(count, function (value, index) {
  38739. copy_1[index] = value;
  38740. });
  38741. return copy_1;
  38742. }
  38743. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38744. if (data instanceof Array) {
  38745. var offset = vertexBuffer.byteOffset / 4;
  38746. return BABYLON.Tools.Slice(data, offset, offset + count);
  38747. }
  38748. else if (data instanceof ArrayBuffer) {
  38749. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38750. }
  38751. else {
  38752. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38753. }
  38754. }
  38755. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38756. return BABYLON.Tools.Slice(data);
  38757. }
  38758. return data;
  38759. };
  38760. /**
  38761. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38762. * @param kind defines the data kind (Position, normal, etc...)
  38763. * @returns true if the vertex buffer with the specified kind is updatable
  38764. */
  38765. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38766. var vb = this._vertexBuffers[kind];
  38767. if (!vb) {
  38768. return false;
  38769. }
  38770. return vb.isUpdatable();
  38771. };
  38772. /**
  38773. * Gets a specific vertex buffer
  38774. * @param kind defines the data kind (Position, normal, etc...)
  38775. * @returns a {BABYLON.VertexBuffer}
  38776. */
  38777. Geometry.prototype.getVertexBuffer = function (kind) {
  38778. if (!this.isReady()) {
  38779. return null;
  38780. }
  38781. return this._vertexBuffers[kind];
  38782. };
  38783. /**
  38784. * Returns all vertex buffers
  38785. * @return an object holding all vertex buffers indexed by kind
  38786. */
  38787. Geometry.prototype.getVertexBuffers = function () {
  38788. if (!this.isReady()) {
  38789. return null;
  38790. }
  38791. return this._vertexBuffers;
  38792. };
  38793. /**
  38794. * Gets a boolean indicating if specific vertex buffer is present
  38795. * @param kind defines the data kind (Position, normal, etc...)
  38796. * @returns true if data is present
  38797. */
  38798. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38799. if (!this._vertexBuffers) {
  38800. if (this._delayInfo) {
  38801. return this._delayInfo.indexOf(kind) !== -1;
  38802. }
  38803. return false;
  38804. }
  38805. return this._vertexBuffers[kind] !== undefined;
  38806. };
  38807. /**
  38808. * Gets a list of all attached data kinds (Position, normal, etc...)
  38809. * @returns a list of string containing all kinds
  38810. */
  38811. Geometry.prototype.getVerticesDataKinds = function () {
  38812. var result = [];
  38813. var kind;
  38814. if (!this._vertexBuffers && this._delayInfo) {
  38815. for (kind in this._delayInfo) {
  38816. result.push(kind);
  38817. }
  38818. }
  38819. else {
  38820. for (kind in this._vertexBuffers) {
  38821. result.push(kind);
  38822. }
  38823. }
  38824. return result;
  38825. };
  38826. /**
  38827. * Update index buffer
  38828. * @param indices defines the indices to store in the index buffer
  38829. * @param offset defines the offset in the target buffer where to store the data
  38830. */
  38831. Geometry.prototype.updateIndices = function (indices, offset) {
  38832. if (!this._indexBuffer) {
  38833. return;
  38834. }
  38835. if (!this._indexBufferIsUpdatable) {
  38836. this.setIndices(indices, null, true);
  38837. }
  38838. else {
  38839. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38840. }
  38841. };
  38842. /**
  38843. * Creates a new index buffer
  38844. * @param indices defines the indices to store in the index buffer
  38845. * @param totalVertices defines the total number of vertices (could be null)
  38846. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38847. */
  38848. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38849. if (totalVertices === void 0) { totalVertices = null; }
  38850. if (updatable === void 0) { updatable = false; }
  38851. if (this._indexBuffer) {
  38852. this._engine._releaseBuffer(this._indexBuffer);
  38853. }
  38854. this._disposeVertexArrayObjects();
  38855. this._indices = indices;
  38856. this._indexBufferIsUpdatable = updatable;
  38857. if (this._meshes.length !== 0 && this._indices) {
  38858. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38859. }
  38860. if (totalVertices != undefined) { // including null and undefined
  38861. this._totalVertices = totalVertices;
  38862. }
  38863. var meshes = this._meshes;
  38864. var numOfMeshes = meshes.length;
  38865. for (var index = 0; index < numOfMeshes; index++) {
  38866. meshes[index]._createGlobalSubMesh(true);
  38867. }
  38868. this.notifyUpdate();
  38869. };
  38870. /**
  38871. * Return the total number of indices
  38872. * @returns the total number of indices
  38873. */
  38874. Geometry.prototype.getTotalIndices = function () {
  38875. if (!this.isReady()) {
  38876. return 0;
  38877. }
  38878. return this._indices.length;
  38879. };
  38880. /**
  38881. * Gets the index buffer array
  38882. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38883. * @returns the index buffer array
  38884. */
  38885. Geometry.prototype.getIndices = function (copyWhenShared) {
  38886. if (!this.isReady()) {
  38887. return null;
  38888. }
  38889. var orig = this._indices;
  38890. if (!copyWhenShared || this._meshes.length === 1) {
  38891. return orig;
  38892. }
  38893. else {
  38894. var len = orig.length;
  38895. var copy = [];
  38896. for (var i = 0; i < len; i++) {
  38897. copy.push(orig[i]);
  38898. }
  38899. return copy;
  38900. }
  38901. };
  38902. /**
  38903. * Gets the index buffer
  38904. * @return the index buffer
  38905. */
  38906. Geometry.prototype.getIndexBuffer = function () {
  38907. if (!this.isReady()) {
  38908. return null;
  38909. }
  38910. return this._indexBuffer;
  38911. };
  38912. /** @hidden */
  38913. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38914. if (effect === void 0) { effect = null; }
  38915. if (!effect || !this._vertexArrayObjects) {
  38916. return;
  38917. }
  38918. if (this._vertexArrayObjects[effect.key]) {
  38919. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38920. delete this._vertexArrayObjects[effect.key];
  38921. }
  38922. };
  38923. /**
  38924. * Release the associated resources for a specific mesh
  38925. * @param mesh defines the source mesh
  38926. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38927. */
  38928. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38929. var meshes = this._meshes;
  38930. var index = meshes.indexOf(mesh);
  38931. if (index === -1) {
  38932. return;
  38933. }
  38934. meshes.splice(index, 1);
  38935. mesh._geometry = null;
  38936. if (meshes.length === 0 && shouldDispose) {
  38937. this.dispose();
  38938. }
  38939. };
  38940. /**
  38941. * Apply current geometry to a given mesh
  38942. * @param mesh defines the mesh to apply geometry to
  38943. */
  38944. Geometry.prototype.applyToMesh = function (mesh) {
  38945. if (mesh._geometry === this) {
  38946. return;
  38947. }
  38948. var previousGeometry = mesh._geometry;
  38949. if (previousGeometry) {
  38950. previousGeometry.releaseForMesh(mesh);
  38951. }
  38952. var meshes = this._meshes;
  38953. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38954. mesh._geometry = this;
  38955. this._scene.pushGeometry(this);
  38956. meshes.push(mesh);
  38957. if (this.isReady()) {
  38958. this._applyToMesh(mesh);
  38959. }
  38960. else {
  38961. mesh._boundingInfo = this._boundingInfo;
  38962. }
  38963. };
  38964. Geometry.prototype._updateExtend = function (data) {
  38965. if (data === void 0) { data = null; }
  38966. if (!data) {
  38967. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38968. }
  38969. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38970. };
  38971. Geometry.prototype._applyToMesh = function (mesh) {
  38972. var numOfMeshes = this._meshes.length;
  38973. // vertexBuffers
  38974. for (var kind in this._vertexBuffers) {
  38975. if (numOfMeshes === 1) {
  38976. this._vertexBuffers[kind].create();
  38977. }
  38978. var buffer = this._vertexBuffers[kind].getBuffer();
  38979. if (buffer)
  38980. buffer.references = numOfMeshes;
  38981. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38982. if (!this._extend) {
  38983. this._updateExtend();
  38984. }
  38985. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38986. mesh._createGlobalSubMesh(false);
  38987. //bounding info was just created again, world matrix should be applied again.
  38988. mesh._updateBoundingInfo();
  38989. }
  38990. }
  38991. // indexBuffer
  38992. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38993. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38994. }
  38995. if (this._indexBuffer) {
  38996. this._indexBuffer.references = numOfMeshes;
  38997. }
  38998. };
  38999. Geometry.prototype.notifyUpdate = function (kind) {
  39000. if (this.onGeometryUpdated) {
  39001. this.onGeometryUpdated(this, kind);
  39002. }
  39003. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39004. var mesh = _a[_i];
  39005. mesh._markSubMeshesAsAttributesDirty();
  39006. }
  39007. };
  39008. /**
  39009. * Load the geometry if it was flagged as delay loaded
  39010. * @param scene defines the hosting scene
  39011. * @param onLoaded defines a callback called when the geometry is loaded
  39012. */
  39013. Geometry.prototype.load = function (scene, onLoaded) {
  39014. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39015. return;
  39016. }
  39017. if (this.isReady()) {
  39018. if (onLoaded) {
  39019. onLoaded();
  39020. }
  39021. return;
  39022. }
  39023. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39024. this._queueLoad(scene, onLoaded);
  39025. };
  39026. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39027. var _this = this;
  39028. if (!this.delayLoadingFile) {
  39029. return;
  39030. }
  39031. scene._addPendingData(this);
  39032. scene._loadFile(this.delayLoadingFile, function (data) {
  39033. if (!_this._delayLoadingFunction) {
  39034. return;
  39035. }
  39036. _this._delayLoadingFunction(JSON.parse(data), _this);
  39037. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39038. _this._delayInfo = [];
  39039. scene._removePendingData(_this);
  39040. var meshes = _this._meshes;
  39041. var numOfMeshes = meshes.length;
  39042. for (var index = 0; index < numOfMeshes; index++) {
  39043. _this._applyToMesh(meshes[index]);
  39044. }
  39045. if (onLoaded) {
  39046. onLoaded();
  39047. }
  39048. }, undefined, true);
  39049. };
  39050. /**
  39051. * Invert the geometry to move from a right handed system to a left handed one.
  39052. */
  39053. Geometry.prototype.toLeftHanded = function () {
  39054. // Flip faces
  39055. var tIndices = this.getIndices(false);
  39056. if (tIndices != null && tIndices.length > 0) {
  39057. for (var i = 0; i < tIndices.length; i += 3) {
  39058. var tTemp = tIndices[i + 0];
  39059. tIndices[i + 0] = tIndices[i + 2];
  39060. tIndices[i + 2] = tTemp;
  39061. }
  39062. this.setIndices(tIndices);
  39063. }
  39064. // Negate position.z
  39065. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39066. if (tPositions != null && tPositions.length > 0) {
  39067. for (var i = 0; i < tPositions.length; i += 3) {
  39068. tPositions[i + 2] = -tPositions[i + 2];
  39069. }
  39070. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39071. }
  39072. // Negate normal.z
  39073. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39074. if (tNormals != null && tNormals.length > 0) {
  39075. for (var i = 0; i < tNormals.length; i += 3) {
  39076. tNormals[i + 2] = -tNormals[i + 2];
  39077. }
  39078. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39079. }
  39080. };
  39081. // Cache
  39082. /** @hidden */
  39083. Geometry.prototype._resetPointsArrayCache = function () {
  39084. this._positions = null;
  39085. };
  39086. /** @hidden */
  39087. Geometry.prototype._generatePointsArray = function () {
  39088. if (this._positions)
  39089. return true;
  39090. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39091. if (!data || data.length === 0) {
  39092. return false;
  39093. }
  39094. this._positions = [];
  39095. for (var index = 0; index < data.length; index += 3) {
  39096. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39097. }
  39098. return true;
  39099. };
  39100. /**
  39101. * Gets a value indicating if the geometry is disposed
  39102. * @returns true if the geometry was disposed
  39103. */
  39104. Geometry.prototype.isDisposed = function () {
  39105. return this._isDisposed;
  39106. };
  39107. Geometry.prototype._disposeVertexArrayObjects = function () {
  39108. if (this._vertexArrayObjects) {
  39109. for (var kind in this._vertexArrayObjects) {
  39110. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39111. }
  39112. this._vertexArrayObjects = {};
  39113. }
  39114. };
  39115. /**
  39116. * Free all associated resources
  39117. */
  39118. Geometry.prototype.dispose = function () {
  39119. var meshes = this._meshes;
  39120. var numOfMeshes = meshes.length;
  39121. var index;
  39122. for (index = 0; index < numOfMeshes; index++) {
  39123. this.releaseForMesh(meshes[index]);
  39124. }
  39125. this._meshes = [];
  39126. this._disposeVertexArrayObjects();
  39127. for (var kind in this._vertexBuffers) {
  39128. this._vertexBuffers[kind].dispose();
  39129. }
  39130. this._vertexBuffers = {};
  39131. this._totalVertices = 0;
  39132. if (this._indexBuffer) {
  39133. this._engine._releaseBuffer(this._indexBuffer);
  39134. }
  39135. this._indexBuffer = null;
  39136. this._indices = [];
  39137. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39138. this.delayLoadingFile = null;
  39139. this._delayLoadingFunction = null;
  39140. this._delayInfo = [];
  39141. this._boundingInfo = null;
  39142. this._scene.removeGeometry(this);
  39143. this._isDisposed = true;
  39144. };
  39145. /**
  39146. * Clone the current geometry into a new geometry
  39147. * @param id defines the unique ID of the new geometry
  39148. * @returns a new geometry object
  39149. */
  39150. Geometry.prototype.copy = function (id) {
  39151. var vertexData = new BABYLON.VertexData();
  39152. vertexData.indices = [];
  39153. var indices = this.getIndices();
  39154. if (indices) {
  39155. for (var index = 0; index < indices.length; index++) {
  39156. vertexData.indices.push(indices[index]);
  39157. }
  39158. }
  39159. var updatable = false;
  39160. var stopChecking = false;
  39161. var kind;
  39162. for (kind in this._vertexBuffers) {
  39163. // using slice() to make a copy of the array and not just reference it
  39164. var data = this.getVerticesData(kind);
  39165. if (data instanceof Float32Array) {
  39166. vertexData.set(new Float32Array(data), kind);
  39167. }
  39168. else {
  39169. vertexData.set(data.slice(0), kind);
  39170. }
  39171. if (!stopChecking) {
  39172. var vb = this.getVertexBuffer(kind);
  39173. if (vb) {
  39174. updatable = vb.isUpdatable();
  39175. stopChecking = !updatable;
  39176. }
  39177. }
  39178. }
  39179. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39180. geometry.delayLoadState = this.delayLoadState;
  39181. geometry.delayLoadingFile = this.delayLoadingFile;
  39182. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39183. for (kind in this._delayInfo) {
  39184. geometry._delayInfo = geometry._delayInfo || [];
  39185. geometry._delayInfo.push(kind);
  39186. }
  39187. // Bounding info
  39188. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39189. return geometry;
  39190. };
  39191. /**
  39192. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39193. * @return a JSON representation of the current geometry data (without the vertices data)
  39194. */
  39195. Geometry.prototype.serialize = function () {
  39196. var serializationObject = {};
  39197. serializationObject.id = this.id;
  39198. serializationObject.updatable = this._updatable;
  39199. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39200. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39201. }
  39202. return serializationObject;
  39203. };
  39204. Geometry.prototype.toNumberArray = function (origin) {
  39205. if (Array.isArray(origin)) {
  39206. return origin;
  39207. }
  39208. else {
  39209. return Array.prototype.slice.call(origin);
  39210. }
  39211. };
  39212. /**
  39213. * Serialize all vertices data into a JSON oject
  39214. * @returns a JSON representation of the current geometry data
  39215. */
  39216. Geometry.prototype.serializeVerticeData = function () {
  39217. var serializationObject = this.serialize();
  39218. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39219. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39220. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39221. serializationObject.positions._updatable = true;
  39222. }
  39223. }
  39224. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39225. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39226. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39227. serializationObject.normals._updatable = true;
  39228. }
  39229. }
  39230. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39231. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39232. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39233. serializationObject.tangets._updatable = true;
  39234. }
  39235. }
  39236. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39237. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39238. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39239. serializationObject.uvs._updatable = true;
  39240. }
  39241. }
  39242. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39243. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39244. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39245. serializationObject.uv2s._updatable = true;
  39246. }
  39247. }
  39248. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39249. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39250. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39251. serializationObject.uv3s._updatable = true;
  39252. }
  39253. }
  39254. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39255. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39256. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39257. serializationObject.uv4s._updatable = true;
  39258. }
  39259. }
  39260. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39261. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39262. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39263. serializationObject.uv5s._updatable = true;
  39264. }
  39265. }
  39266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39267. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39268. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39269. serializationObject.uv6s._updatable = true;
  39270. }
  39271. }
  39272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39273. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39274. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39275. serializationObject.colors._updatable = true;
  39276. }
  39277. }
  39278. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39279. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39280. serializationObject.matricesIndices._isExpanded = true;
  39281. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39282. serializationObject.matricesIndices._updatable = true;
  39283. }
  39284. }
  39285. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39286. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39287. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39288. serializationObject.matricesWeights._updatable = true;
  39289. }
  39290. }
  39291. serializationObject.indices = this.toNumberArray(this.getIndices());
  39292. return serializationObject;
  39293. };
  39294. // Statics
  39295. /**
  39296. * Extracts a clone of a mesh geometry
  39297. * @param mesh defines the source mesh
  39298. * @param id defines the unique ID of the new geometry object
  39299. * @returns the new geometry object
  39300. */
  39301. Geometry.ExtractFromMesh = function (mesh, id) {
  39302. var geometry = mesh._geometry;
  39303. if (!geometry) {
  39304. return null;
  39305. }
  39306. return geometry.copy(id);
  39307. };
  39308. /**
  39309. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39310. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39311. * Be aware Math.random() could cause collisions, but:
  39312. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  39313. * @returns a string containing a new GUID
  39314. */
  39315. Geometry.RandomId = function () {
  39316. return BABYLON.Tools.RandomId();
  39317. };
  39318. /** @hidden */
  39319. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39320. var scene = mesh.getScene();
  39321. // Geometry
  39322. var geometryId = parsedGeometry.geometryId;
  39323. if (geometryId) {
  39324. var geometry = scene.getGeometryByID(geometryId);
  39325. if (geometry) {
  39326. geometry.applyToMesh(mesh);
  39327. }
  39328. }
  39329. else if (parsedGeometry instanceof ArrayBuffer) {
  39330. var binaryInfo = mesh._binaryInfo;
  39331. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39332. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39333. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39334. }
  39335. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39336. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39337. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39338. }
  39339. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39340. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39341. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39342. }
  39343. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39344. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39345. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39346. }
  39347. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39348. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39349. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39350. }
  39351. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39352. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39353. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39354. }
  39355. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39356. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39357. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39358. }
  39359. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39360. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39361. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39362. }
  39363. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39364. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39365. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39366. }
  39367. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39368. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39369. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39370. }
  39371. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39372. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39373. var floatIndices = [];
  39374. for (var i = 0; i < matricesIndicesData.length; i++) {
  39375. var index = matricesIndicesData[i];
  39376. floatIndices.push(index & 0x000000FF);
  39377. floatIndices.push((index & 0x0000FF00) >> 8);
  39378. floatIndices.push((index & 0x00FF0000) >> 16);
  39379. floatIndices.push(index >> 24);
  39380. }
  39381. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39382. }
  39383. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39384. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39385. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39386. }
  39387. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39388. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39389. mesh.setIndices(indicesData, null);
  39390. }
  39391. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39392. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39393. mesh.subMeshes = [];
  39394. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39395. var materialIndex = subMeshesData[(i * 5) + 0];
  39396. var verticesStart = subMeshesData[(i * 5) + 1];
  39397. var verticesCount = subMeshesData[(i * 5) + 2];
  39398. var indexStart = subMeshesData[(i * 5) + 3];
  39399. var indexCount = subMeshesData[(i * 5) + 4];
  39400. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39401. }
  39402. }
  39403. }
  39404. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39405. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39406. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39407. if (parsedGeometry.tangents) {
  39408. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39409. }
  39410. if (parsedGeometry.uvs) {
  39411. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39412. }
  39413. if (parsedGeometry.uvs2) {
  39414. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39415. }
  39416. if (parsedGeometry.uvs3) {
  39417. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39418. }
  39419. if (parsedGeometry.uvs4) {
  39420. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39421. }
  39422. if (parsedGeometry.uvs5) {
  39423. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39424. }
  39425. if (parsedGeometry.uvs6) {
  39426. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39427. }
  39428. if (parsedGeometry.colors) {
  39429. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39430. }
  39431. if (parsedGeometry.matricesIndices) {
  39432. if (!parsedGeometry.matricesIndices._isExpanded) {
  39433. var floatIndices = [];
  39434. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39435. var matricesIndex = parsedGeometry.matricesIndices[i];
  39436. floatIndices.push(matricesIndex & 0x000000FF);
  39437. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39438. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39439. floatIndices.push(matricesIndex >> 24);
  39440. }
  39441. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39442. }
  39443. else {
  39444. delete parsedGeometry.matricesIndices._isExpanded;
  39445. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39446. }
  39447. }
  39448. if (parsedGeometry.matricesIndicesExtra) {
  39449. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39450. var floatIndices = [];
  39451. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39452. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39453. floatIndices.push(matricesIndex & 0x000000FF);
  39454. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39455. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39456. floatIndices.push(matricesIndex >> 24);
  39457. }
  39458. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39459. }
  39460. else {
  39461. delete parsedGeometry.matricesIndices._isExpanded;
  39462. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39463. }
  39464. }
  39465. if (parsedGeometry.matricesWeights) {
  39466. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39467. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39468. }
  39469. if (parsedGeometry.matricesWeightsExtra) {
  39470. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39471. }
  39472. mesh.setIndices(parsedGeometry.indices, null);
  39473. }
  39474. // SubMeshes
  39475. if (parsedGeometry.subMeshes) {
  39476. mesh.subMeshes = [];
  39477. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39478. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39479. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39480. }
  39481. }
  39482. // Flat shading
  39483. if (mesh._shouldGenerateFlatShading) {
  39484. mesh.convertToFlatShadedMesh();
  39485. delete mesh._shouldGenerateFlatShading;
  39486. }
  39487. // Update
  39488. mesh.computeWorldMatrix(true);
  39489. // Octree
  39490. var sceneOctree = scene.selectionOctree;
  39491. if (sceneOctree !== undefined && sceneOctree !== null) {
  39492. sceneOctree.addMesh(mesh);
  39493. }
  39494. };
  39495. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39496. var epsilon = 1e-3;
  39497. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39498. return;
  39499. }
  39500. var noInfluenceBoneIndex = 0.0;
  39501. if (parsedGeometry.skeletonId > -1) {
  39502. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39503. if (!skeleton) {
  39504. return;
  39505. }
  39506. noInfluenceBoneIndex = skeleton.bones.length;
  39507. }
  39508. else {
  39509. return;
  39510. }
  39511. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39512. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39513. var matricesWeights = parsedGeometry.matricesWeights;
  39514. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39515. var influencers = parsedGeometry.numBoneInfluencer;
  39516. var size = matricesWeights.length;
  39517. for (var i = 0; i < size; i += 4) {
  39518. var weight = 0.0;
  39519. var firstZeroWeight = -1;
  39520. for (var j = 0; j < 4; j++) {
  39521. var w = matricesWeights[i + j];
  39522. weight += w;
  39523. if (w < epsilon && firstZeroWeight < 0) {
  39524. firstZeroWeight = j;
  39525. }
  39526. }
  39527. if (matricesWeightsExtra) {
  39528. for (var j = 0; j < 4; j++) {
  39529. var w = matricesWeightsExtra[i + j];
  39530. weight += w;
  39531. if (w < epsilon && firstZeroWeight < 0) {
  39532. firstZeroWeight = j + 4;
  39533. }
  39534. }
  39535. }
  39536. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39537. firstZeroWeight = influencers - 1;
  39538. }
  39539. if (weight > epsilon) {
  39540. var mweight = 1.0 / weight;
  39541. for (var j = 0; j < 4; j++) {
  39542. matricesWeights[i + j] *= mweight;
  39543. }
  39544. if (matricesWeightsExtra) {
  39545. for (var j = 0; j < 4; j++) {
  39546. matricesWeightsExtra[i + j] *= mweight;
  39547. }
  39548. }
  39549. }
  39550. else {
  39551. if (firstZeroWeight >= 4) {
  39552. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39553. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39554. }
  39555. else {
  39556. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39557. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39558. }
  39559. }
  39560. }
  39561. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39562. if (parsedGeometry.matricesWeightsExtra) {
  39563. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39564. }
  39565. };
  39566. /**
  39567. * Create a new geometry from persisted data (Using .babylon file format)
  39568. * @param parsedVertexData defines the persisted data
  39569. * @param scene defines the hosting scene
  39570. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39571. * @returns the new geometry object
  39572. */
  39573. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39574. if (scene.getGeometryByID(parsedVertexData.id)) {
  39575. return null; // null since geometry could be something else than a box...
  39576. }
  39577. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39578. if (BABYLON.Tags) {
  39579. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39580. }
  39581. if (parsedVertexData.delayLoadingFile) {
  39582. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39583. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39584. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39585. geometry._delayInfo = [];
  39586. if (parsedVertexData.hasUVs) {
  39587. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39588. }
  39589. if (parsedVertexData.hasUVs2) {
  39590. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39591. }
  39592. if (parsedVertexData.hasUVs3) {
  39593. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39594. }
  39595. if (parsedVertexData.hasUVs4) {
  39596. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39597. }
  39598. if (parsedVertexData.hasUVs5) {
  39599. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39600. }
  39601. if (parsedVertexData.hasUVs6) {
  39602. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39603. }
  39604. if (parsedVertexData.hasColors) {
  39605. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39606. }
  39607. if (parsedVertexData.hasMatricesIndices) {
  39608. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39609. }
  39610. if (parsedVertexData.hasMatricesWeights) {
  39611. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39612. }
  39613. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39614. }
  39615. else {
  39616. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39617. }
  39618. scene.pushGeometry(geometry, true);
  39619. return geometry;
  39620. };
  39621. return Geometry;
  39622. }());
  39623. BABYLON.Geometry = Geometry;
  39624. // Primitives
  39625. /// Abstract class
  39626. /**
  39627. * Abstract class used to provide common services for all typed geometries
  39628. * @hidden
  39629. */
  39630. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39631. __extends(_PrimitiveGeometry, _super);
  39632. /**
  39633. * Creates a new typed geometry
  39634. * @param id defines the unique ID of the geometry
  39635. * @param scene defines the hosting scene
  39636. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39637. * @param mesh defines the hosting mesh (can be null)
  39638. */
  39639. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39640. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39641. if (mesh === void 0) { mesh = null; }
  39642. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39643. _this._canBeRegenerated = _canBeRegenerated;
  39644. _this._beingRegenerated = true;
  39645. _this.regenerate();
  39646. _this._beingRegenerated = false;
  39647. return _this;
  39648. }
  39649. /**
  39650. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39651. * @returns true if the geometry can be regenerated
  39652. */
  39653. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39654. return this._canBeRegenerated;
  39655. };
  39656. /**
  39657. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39658. */
  39659. _PrimitiveGeometry.prototype.regenerate = function () {
  39660. if (!this._canBeRegenerated) {
  39661. return;
  39662. }
  39663. this._beingRegenerated = true;
  39664. this.setAllVerticesData(this._regenerateVertexData(), false);
  39665. this._beingRegenerated = false;
  39666. };
  39667. /**
  39668. * Clone the geometry
  39669. * @param id defines the unique ID of the new geometry
  39670. * @returns the new geometry
  39671. */
  39672. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39673. return _super.prototype.copy.call(this, id);
  39674. };
  39675. // overrides
  39676. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39677. if (!this._beingRegenerated) {
  39678. return;
  39679. }
  39680. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39681. };
  39682. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39683. if (!this._beingRegenerated) {
  39684. return;
  39685. }
  39686. _super.prototype.setVerticesData.call(this, kind, data, false);
  39687. };
  39688. // to override
  39689. /** @hidden */
  39690. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39691. throw new Error("Abstract method");
  39692. };
  39693. _PrimitiveGeometry.prototype.copy = function (id) {
  39694. throw new Error("Must be overriden in sub-classes.");
  39695. };
  39696. _PrimitiveGeometry.prototype.serialize = function () {
  39697. var serializationObject = _super.prototype.serialize.call(this);
  39698. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39699. return serializationObject;
  39700. };
  39701. return _PrimitiveGeometry;
  39702. }(Geometry));
  39703. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39704. /**
  39705. * Creates a ribbon geometry
  39706. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39707. */
  39708. var RibbonGeometry = /** @class */ (function (_super) {
  39709. __extends(RibbonGeometry, _super);
  39710. /**
  39711. * Creates a ribbon geometry
  39712. * @param id defines the unique ID of the geometry
  39713. * @param scene defines the hosting scene
  39714. * @param pathArray defines the array of paths to use
  39715. * @param closeArray defines if the last path and the first path must be joined
  39716. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39717. * @param offset defines the offset between points
  39718. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39719. * @param mesh defines the hosting mesh (can be null)
  39720. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39721. */
  39722. function RibbonGeometry(id, scene,
  39723. /**
  39724. * Defines the array of paths to use
  39725. */
  39726. pathArray,
  39727. /**
  39728. * Defines if the last and first points of each path in your pathArray must be joined
  39729. */
  39730. closeArray,
  39731. /**
  39732. * Defines if the last and first points of each path in your pathArray must be joined
  39733. */
  39734. closePath,
  39735. /**
  39736. * Defines the offset between points
  39737. */
  39738. offset, canBeRegenerated, mesh,
  39739. /**
  39740. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39741. */
  39742. side) {
  39743. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39744. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39745. _this.pathArray = pathArray;
  39746. _this.closeArray = closeArray;
  39747. _this.closePath = closePath;
  39748. _this.offset = offset;
  39749. _this.side = side;
  39750. return _this;
  39751. }
  39752. /** @hidden */
  39753. RibbonGeometry.prototype._regenerateVertexData = function () {
  39754. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39755. };
  39756. RibbonGeometry.prototype.copy = function (id) {
  39757. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39758. };
  39759. return RibbonGeometry;
  39760. }(_PrimitiveGeometry));
  39761. BABYLON.RibbonGeometry = RibbonGeometry;
  39762. /**
  39763. * Creates a box geometry
  39764. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39765. */
  39766. var BoxGeometry = /** @class */ (function (_super) {
  39767. __extends(BoxGeometry, _super);
  39768. /**
  39769. * Creates a box geometry
  39770. * @param id defines the unique ID of the geometry
  39771. * @param scene defines the hosting scene
  39772. * @param size defines the zise of the box (width, height and depth are the same)
  39773. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39774. * @param mesh defines the hosting mesh (can be null)
  39775. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39776. */
  39777. function BoxGeometry(id, scene,
  39778. /**
  39779. * Defines the zise of the box (width, height and depth are the same)
  39780. */
  39781. size, canBeRegenerated, mesh,
  39782. /**
  39783. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39784. */
  39785. side) {
  39786. if (mesh === void 0) { mesh = null; }
  39787. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39788. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39789. _this.size = size;
  39790. _this.side = side;
  39791. return _this;
  39792. }
  39793. BoxGeometry.prototype._regenerateVertexData = function () {
  39794. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39795. };
  39796. BoxGeometry.prototype.copy = function (id) {
  39797. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39798. };
  39799. BoxGeometry.prototype.serialize = function () {
  39800. var serializationObject = _super.prototype.serialize.call(this);
  39801. serializationObject.size = this.size;
  39802. return serializationObject;
  39803. };
  39804. BoxGeometry.Parse = function (parsedBox, scene) {
  39805. if (scene.getGeometryByID(parsedBox.id)) {
  39806. return null; // null since geometry could be something else than a box...
  39807. }
  39808. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39809. if (BABYLON.Tags) {
  39810. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39811. }
  39812. scene.pushGeometry(box, true);
  39813. return box;
  39814. };
  39815. return BoxGeometry;
  39816. }(_PrimitiveGeometry));
  39817. BABYLON.BoxGeometry = BoxGeometry;
  39818. /**
  39819. * Creates a sphere geometry
  39820. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39821. */
  39822. var SphereGeometry = /** @class */ (function (_super) {
  39823. __extends(SphereGeometry, _super);
  39824. /**
  39825. * Create a new sphere geometry
  39826. * @param id defines the unique ID of the geometry
  39827. * @param scene defines the hosting scene
  39828. * @param segments defines the number of segments to use to create the sphere
  39829. * @param diameter defines the diameter of the sphere
  39830. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39831. * @param mesh defines the hosting mesh (can be null)
  39832. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39833. */
  39834. function SphereGeometry(id, scene,
  39835. /**
  39836. * Defines the number of segments to use to create the sphere
  39837. */
  39838. segments,
  39839. /**
  39840. * Defines the diameter of the sphere
  39841. */
  39842. diameter, canBeRegenerated, mesh,
  39843. /**
  39844. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39845. */
  39846. side) {
  39847. if (mesh === void 0) { mesh = null; }
  39848. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39849. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39850. _this.segments = segments;
  39851. _this.diameter = diameter;
  39852. _this.side = side;
  39853. return _this;
  39854. }
  39855. SphereGeometry.prototype._regenerateVertexData = function () {
  39856. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39857. };
  39858. SphereGeometry.prototype.copy = function (id) {
  39859. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39860. };
  39861. SphereGeometry.prototype.serialize = function () {
  39862. var serializationObject = _super.prototype.serialize.call(this);
  39863. serializationObject.segments = this.segments;
  39864. serializationObject.diameter = this.diameter;
  39865. return serializationObject;
  39866. };
  39867. SphereGeometry.Parse = function (parsedSphere, scene) {
  39868. if (scene.getGeometryByID(parsedSphere.id)) {
  39869. return null; // null since geometry could be something else than a sphere...
  39870. }
  39871. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39872. if (BABYLON.Tags) {
  39873. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39874. }
  39875. scene.pushGeometry(sphere, true);
  39876. return sphere;
  39877. };
  39878. return SphereGeometry;
  39879. }(_PrimitiveGeometry));
  39880. BABYLON.SphereGeometry = SphereGeometry;
  39881. /**
  39882. * Creates a disc geometry
  39883. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39884. */
  39885. var DiscGeometry = /** @class */ (function (_super) {
  39886. __extends(DiscGeometry, _super);
  39887. /**
  39888. * Creates a new disc geometry
  39889. * @param id defines the unique ID of the geometry
  39890. * @param scene defines the hosting scene
  39891. * @param radius defines the radius of the disc
  39892. * @param tessellation defines the tesselation factor to apply to the disc
  39893. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39894. * @param mesh defines the hosting mesh (can be null)
  39895. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39896. */
  39897. function DiscGeometry(id, scene,
  39898. /**
  39899. * Defines the radius of the disc
  39900. */
  39901. radius,
  39902. /**
  39903. * Defines the tesselation factor to apply to the disc
  39904. */
  39905. tessellation, canBeRegenerated, mesh,
  39906. /**
  39907. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39908. */
  39909. side) {
  39910. if (mesh === void 0) { mesh = null; }
  39911. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39912. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39913. _this.radius = radius;
  39914. _this.tessellation = tessellation;
  39915. _this.side = side;
  39916. return _this;
  39917. }
  39918. DiscGeometry.prototype._regenerateVertexData = function () {
  39919. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39920. };
  39921. DiscGeometry.prototype.copy = function (id) {
  39922. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39923. };
  39924. return DiscGeometry;
  39925. }(_PrimitiveGeometry));
  39926. BABYLON.DiscGeometry = DiscGeometry;
  39927. /**
  39928. * Creates a new cylinder geometry
  39929. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39930. */
  39931. var CylinderGeometry = /** @class */ (function (_super) {
  39932. __extends(CylinderGeometry, _super);
  39933. /**
  39934. * Creates a new cylinder geometry
  39935. * @param id defines the unique ID of the geometry
  39936. * @param scene defines the hosting scene
  39937. * @param height defines the height of the cylinder
  39938. * @param diameterTop defines the diameter of the cylinder's top cap
  39939. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39940. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39941. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39942. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39943. * @param mesh defines the hosting mesh (can be null)
  39944. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39945. */
  39946. function CylinderGeometry(id, scene,
  39947. /**
  39948. * Defines the height of the cylinder
  39949. */
  39950. height,
  39951. /**
  39952. * Defines the diameter of the cylinder's top cap
  39953. */
  39954. diameterTop,
  39955. /**
  39956. * Defines the diameter of the cylinder's bottom cap
  39957. */
  39958. diameterBottom,
  39959. /**
  39960. * Defines the tessellation factor to apply to the cylinder
  39961. */
  39962. tessellation,
  39963. /**
  39964. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39965. */
  39966. subdivisions, canBeRegenerated, mesh,
  39967. /**
  39968. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39969. */
  39970. side) {
  39971. if (subdivisions === void 0) { subdivisions = 1; }
  39972. if (mesh === void 0) { mesh = null; }
  39973. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39974. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39975. _this.height = height;
  39976. _this.diameterTop = diameterTop;
  39977. _this.diameterBottom = diameterBottom;
  39978. _this.tessellation = tessellation;
  39979. _this.subdivisions = subdivisions;
  39980. _this.side = side;
  39981. return _this;
  39982. }
  39983. CylinderGeometry.prototype._regenerateVertexData = function () {
  39984. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39985. };
  39986. CylinderGeometry.prototype.copy = function (id) {
  39987. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39988. };
  39989. CylinderGeometry.prototype.serialize = function () {
  39990. var serializationObject = _super.prototype.serialize.call(this);
  39991. serializationObject.height = this.height;
  39992. serializationObject.diameterTop = this.diameterTop;
  39993. serializationObject.diameterBottom = this.diameterBottom;
  39994. serializationObject.tessellation = this.tessellation;
  39995. return serializationObject;
  39996. };
  39997. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39998. if (scene.getGeometryByID(parsedCylinder.id)) {
  39999. return null; // null since geometry could be something else than a cylinder...
  40000. }
  40001. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40002. if (BABYLON.Tags) {
  40003. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40004. }
  40005. scene.pushGeometry(cylinder, true);
  40006. return cylinder;
  40007. };
  40008. return CylinderGeometry;
  40009. }(_PrimitiveGeometry));
  40010. BABYLON.CylinderGeometry = CylinderGeometry;
  40011. /**
  40012. * Creates a new torus geometry
  40013. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40014. */
  40015. var TorusGeometry = /** @class */ (function (_super) {
  40016. __extends(TorusGeometry, _super);
  40017. /**
  40018. * Creates a new torus geometry
  40019. * @param id defines the unique ID of the geometry
  40020. * @param scene defines the hosting scene
  40021. * @param diameter defines the diameter of the torus
  40022. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40023. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40024. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40025. * @param mesh defines the hosting mesh (can be null)
  40026. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40027. */
  40028. function TorusGeometry(id, scene,
  40029. /**
  40030. * Defines the diameter of the torus
  40031. */
  40032. diameter,
  40033. /**
  40034. * Defines the thickness of the torus (ie. internal diameter)
  40035. */
  40036. thickness,
  40037. /**
  40038. * Defines the tesselation factor to apply to the torus
  40039. */
  40040. tessellation, canBeRegenerated, mesh,
  40041. /**
  40042. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40043. */
  40044. side) {
  40045. if (mesh === void 0) { mesh = null; }
  40046. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40047. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40048. _this.diameter = diameter;
  40049. _this.thickness = thickness;
  40050. _this.tessellation = tessellation;
  40051. _this.side = side;
  40052. return _this;
  40053. }
  40054. TorusGeometry.prototype._regenerateVertexData = function () {
  40055. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40056. };
  40057. TorusGeometry.prototype.copy = function (id) {
  40058. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40059. };
  40060. TorusGeometry.prototype.serialize = function () {
  40061. var serializationObject = _super.prototype.serialize.call(this);
  40062. serializationObject.diameter = this.diameter;
  40063. serializationObject.thickness = this.thickness;
  40064. serializationObject.tessellation = this.tessellation;
  40065. return serializationObject;
  40066. };
  40067. TorusGeometry.Parse = function (parsedTorus, scene) {
  40068. if (scene.getGeometryByID(parsedTorus.id)) {
  40069. return null; // null since geometry could be something else than a torus...
  40070. }
  40071. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40072. if (BABYLON.Tags) {
  40073. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40074. }
  40075. scene.pushGeometry(torus, true);
  40076. return torus;
  40077. };
  40078. return TorusGeometry;
  40079. }(_PrimitiveGeometry));
  40080. BABYLON.TorusGeometry = TorusGeometry;
  40081. /**
  40082. * Creates a new ground geometry
  40083. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40084. */
  40085. var GroundGeometry = /** @class */ (function (_super) {
  40086. __extends(GroundGeometry, _super);
  40087. /**
  40088. * Creates a new ground geometry
  40089. * @param id defines the unique ID of the geometry
  40090. * @param scene defines the hosting scene
  40091. * @param width defines the width of the ground
  40092. * @param height defines the height of the ground
  40093. * @param subdivisions defines the subdivisions to apply to the ground
  40094. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40095. * @param mesh defines the hosting mesh (can be null)
  40096. */
  40097. function GroundGeometry(id, scene,
  40098. /**
  40099. * Defines the width of the ground
  40100. */
  40101. width,
  40102. /**
  40103. * Defines the height of the ground
  40104. */
  40105. height,
  40106. /**
  40107. * Defines the subdivisions to apply to the ground
  40108. */
  40109. subdivisions, canBeRegenerated, mesh) {
  40110. if (mesh === void 0) { mesh = null; }
  40111. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40112. _this.width = width;
  40113. _this.height = height;
  40114. _this.subdivisions = subdivisions;
  40115. return _this;
  40116. }
  40117. GroundGeometry.prototype._regenerateVertexData = function () {
  40118. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40119. };
  40120. GroundGeometry.prototype.copy = function (id) {
  40121. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40122. };
  40123. GroundGeometry.prototype.serialize = function () {
  40124. var serializationObject = _super.prototype.serialize.call(this);
  40125. serializationObject.width = this.width;
  40126. serializationObject.height = this.height;
  40127. serializationObject.subdivisions = this.subdivisions;
  40128. return serializationObject;
  40129. };
  40130. GroundGeometry.Parse = function (parsedGround, scene) {
  40131. if (scene.getGeometryByID(parsedGround.id)) {
  40132. return null; // null since geometry could be something else than a ground...
  40133. }
  40134. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40135. if (BABYLON.Tags) {
  40136. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40137. }
  40138. scene.pushGeometry(ground, true);
  40139. return ground;
  40140. };
  40141. return GroundGeometry;
  40142. }(_PrimitiveGeometry));
  40143. BABYLON.GroundGeometry = GroundGeometry;
  40144. /**
  40145. * Creates a tiled ground geometry
  40146. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40147. */
  40148. var TiledGroundGeometry = /** @class */ (function (_super) {
  40149. __extends(TiledGroundGeometry, _super);
  40150. /**
  40151. * Creates a tiled ground geometry
  40152. * @param id defines the unique ID of the geometry
  40153. * @param scene defines the hosting scene
  40154. * @param xmin defines the minimum value on X axis
  40155. * @param zmin defines the minimum value on Z axis
  40156. * @param xmax defines the maximum value on X axis
  40157. * @param zmax defines the maximum value on Z axis
  40158. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40159. * @param precision defines the precision to use when computing the tiles
  40160. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40161. * @param mesh defines the hosting mesh (can be null)
  40162. */
  40163. function TiledGroundGeometry(id, scene,
  40164. /**
  40165. * Defines the minimum value on X axis
  40166. */
  40167. xmin,
  40168. /**
  40169. * Defines the minimum value on Z axis
  40170. */
  40171. zmin,
  40172. /**
  40173. * Defines the maximum value on X axis
  40174. */
  40175. xmax,
  40176. /**
  40177. * Defines the maximum value on Z axis
  40178. */
  40179. zmax,
  40180. /**
  40181. * Defines the subdivisions to apply to the ground
  40182. */
  40183. subdivisions,
  40184. /**
  40185. * Defines the precision to use when computing the tiles
  40186. */
  40187. precision, canBeRegenerated, mesh) {
  40188. if (mesh === void 0) { mesh = null; }
  40189. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40190. _this.xmin = xmin;
  40191. _this.zmin = zmin;
  40192. _this.xmax = xmax;
  40193. _this.zmax = zmax;
  40194. _this.subdivisions = subdivisions;
  40195. _this.precision = precision;
  40196. return _this;
  40197. }
  40198. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40199. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40200. };
  40201. TiledGroundGeometry.prototype.copy = function (id) {
  40202. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40203. };
  40204. return TiledGroundGeometry;
  40205. }(_PrimitiveGeometry));
  40206. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40207. /**
  40208. * Creates a plane geometry
  40209. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40210. */
  40211. var PlaneGeometry = /** @class */ (function (_super) {
  40212. __extends(PlaneGeometry, _super);
  40213. /**
  40214. * Creates a plane geometry
  40215. * @param id defines the unique ID of the geometry
  40216. * @param scene defines the hosting scene
  40217. * @param size defines the size of the plane (width === height)
  40218. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40219. * @param mesh defines the hosting mesh (can be null)
  40220. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40221. */
  40222. function PlaneGeometry(id, scene,
  40223. /**
  40224. * Defines the size of the plane (width === height)
  40225. */
  40226. size, canBeRegenerated, mesh,
  40227. /**
  40228. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40229. */
  40230. side) {
  40231. if (mesh === void 0) { mesh = null; }
  40232. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40233. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40234. _this.size = size;
  40235. _this.side = side;
  40236. return _this;
  40237. }
  40238. PlaneGeometry.prototype._regenerateVertexData = function () {
  40239. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40240. };
  40241. PlaneGeometry.prototype.copy = function (id) {
  40242. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40243. };
  40244. PlaneGeometry.prototype.serialize = function () {
  40245. var serializationObject = _super.prototype.serialize.call(this);
  40246. serializationObject.size = this.size;
  40247. return serializationObject;
  40248. };
  40249. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40250. if (scene.getGeometryByID(parsedPlane.id)) {
  40251. return null; // null since geometry could be something else than a ground...
  40252. }
  40253. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40254. if (BABYLON.Tags) {
  40255. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40256. }
  40257. scene.pushGeometry(plane, true);
  40258. return plane;
  40259. };
  40260. return PlaneGeometry;
  40261. }(_PrimitiveGeometry));
  40262. BABYLON.PlaneGeometry = PlaneGeometry;
  40263. /**
  40264. * Creates a torus knot geometry
  40265. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40266. */
  40267. var TorusKnotGeometry = /** @class */ (function (_super) {
  40268. __extends(TorusKnotGeometry, _super);
  40269. /**
  40270. * Creates a torus knot geometry
  40271. * @param id defines the unique ID of the geometry
  40272. * @param scene defines the hosting scene
  40273. * @param radius defines the radius of the torus knot
  40274. * @param tube defines the thickness of the torus knot tube
  40275. * @param radialSegments defines the number of radial segments
  40276. * @param tubularSegments defines the number of tubular segments
  40277. * @param p defines the first number of windings
  40278. * @param q defines the second number of windings
  40279. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40280. * @param mesh defines the hosting mesh (can be null)
  40281. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40282. */
  40283. function TorusKnotGeometry(id, scene,
  40284. /**
  40285. * Defines the radius of the torus knot
  40286. */
  40287. radius,
  40288. /**
  40289. * Defines the thickness of the torus knot tube
  40290. */
  40291. tube,
  40292. /**
  40293. * Defines the number of radial segments
  40294. */
  40295. radialSegments,
  40296. /**
  40297. * Defines the number of tubular segments
  40298. */
  40299. tubularSegments,
  40300. /**
  40301. * Defines the first number of windings
  40302. */
  40303. p,
  40304. /**
  40305. * Defines the second number of windings
  40306. */
  40307. q, canBeRegenerated, mesh,
  40308. /**
  40309. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40310. */
  40311. side) {
  40312. if (mesh === void 0) { mesh = null; }
  40313. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40314. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40315. _this.radius = radius;
  40316. _this.tube = tube;
  40317. _this.radialSegments = radialSegments;
  40318. _this.tubularSegments = tubularSegments;
  40319. _this.p = p;
  40320. _this.q = q;
  40321. _this.side = side;
  40322. return _this;
  40323. }
  40324. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40325. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  40326. };
  40327. TorusKnotGeometry.prototype.copy = function (id) {
  40328. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40329. };
  40330. TorusKnotGeometry.prototype.serialize = function () {
  40331. var serializationObject = _super.prototype.serialize.call(this);
  40332. serializationObject.radius = this.radius;
  40333. serializationObject.tube = this.tube;
  40334. serializationObject.radialSegments = this.radialSegments;
  40335. serializationObject.tubularSegments = this.tubularSegments;
  40336. serializationObject.p = this.p;
  40337. serializationObject.q = this.q;
  40338. return serializationObject;
  40339. };
  40340. ;
  40341. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40342. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40343. return null; // null since geometry could be something else than a ground...
  40344. }
  40345. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40346. if (BABYLON.Tags) {
  40347. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40348. }
  40349. scene.pushGeometry(torusKnot, true);
  40350. return torusKnot;
  40351. };
  40352. return TorusKnotGeometry;
  40353. }(_PrimitiveGeometry));
  40354. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40355. //}
  40356. })(BABYLON || (BABYLON = {}));
  40357. //# sourceMappingURL=babylon.geometry.js.map
  40358. var BABYLON;
  40359. (function (BABYLON) {
  40360. /**
  40361. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40362. */
  40363. var PerformanceMonitor = /** @class */ (function () {
  40364. /**
  40365. * constructor
  40366. * @param frameSampleSize The number of samples required to saturate the sliding window
  40367. */
  40368. function PerformanceMonitor(frameSampleSize) {
  40369. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40370. this._enabled = true;
  40371. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40372. }
  40373. /**
  40374. * Samples current frame
  40375. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40376. */
  40377. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40378. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40379. if (!this._enabled)
  40380. return;
  40381. if (this._lastFrameTimeMs != null) {
  40382. var dt = timeMs - this._lastFrameTimeMs;
  40383. this._rollingFrameTime.add(dt);
  40384. }
  40385. this._lastFrameTimeMs = timeMs;
  40386. };
  40387. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40388. /**
  40389. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40390. * @return Average frame time in milliseconds
  40391. */
  40392. get: function () {
  40393. return this._rollingFrameTime.average;
  40394. },
  40395. enumerable: true,
  40396. configurable: true
  40397. });
  40398. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40399. /**
  40400. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40401. * @return Frame time variance in milliseconds squared
  40402. */
  40403. get: function () {
  40404. return this._rollingFrameTime.variance;
  40405. },
  40406. enumerable: true,
  40407. configurable: true
  40408. });
  40409. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40410. /**
  40411. * Returns the frame time of the most recent frame
  40412. * @return Frame time in milliseconds
  40413. */
  40414. get: function () {
  40415. return this._rollingFrameTime.history(0);
  40416. },
  40417. enumerable: true,
  40418. configurable: true
  40419. });
  40420. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40421. /**
  40422. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40423. * @return Framerate in frames per second
  40424. */
  40425. get: function () {
  40426. return 1000.0 / this._rollingFrameTime.average;
  40427. },
  40428. enumerable: true,
  40429. configurable: true
  40430. });
  40431. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40432. /**
  40433. * Returns the average framerate in frames per second using the most recent frame time
  40434. * @return Framerate in frames per second
  40435. */
  40436. get: function () {
  40437. var history = this._rollingFrameTime.history(0);
  40438. if (history === 0) {
  40439. return 0;
  40440. }
  40441. return 1000.0 / history;
  40442. },
  40443. enumerable: true,
  40444. configurable: true
  40445. });
  40446. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40447. /**
  40448. * Returns true if enough samples have been taken to completely fill the sliding window
  40449. * @return true if saturated
  40450. */
  40451. get: function () {
  40452. return this._rollingFrameTime.isSaturated();
  40453. },
  40454. enumerable: true,
  40455. configurable: true
  40456. });
  40457. /**
  40458. * Enables contributions to the sliding window sample set
  40459. */
  40460. PerformanceMonitor.prototype.enable = function () {
  40461. this._enabled = true;
  40462. };
  40463. /**
  40464. * Disables contributions to the sliding window sample set
  40465. * Samples will not be interpolated over the disabled period
  40466. */
  40467. PerformanceMonitor.prototype.disable = function () {
  40468. this._enabled = false;
  40469. //clear last sample to avoid interpolating over the disabled period when next enabled
  40470. this._lastFrameTimeMs = null;
  40471. };
  40472. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40473. /**
  40474. * Returns true if sampling is enabled
  40475. * @return true if enabled
  40476. */
  40477. get: function () {
  40478. return this._enabled;
  40479. },
  40480. enumerable: true,
  40481. configurable: true
  40482. });
  40483. /**
  40484. * Resets performance monitor
  40485. */
  40486. PerformanceMonitor.prototype.reset = function () {
  40487. //clear last sample to avoid interpolating over the disabled period when next enabled
  40488. this._lastFrameTimeMs = null;
  40489. //wipe record
  40490. this._rollingFrameTime.reset();
  40491. };
  40492. return PerformanceMonitor;
  40493. }());
  40494. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40495. /**
  40496. * RollingAverage
  40497. *
  40498. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40499. */
  40500. var RollingAverage = /** @class */ (function () {
  40501. /**
  40502. * constructor
  40503. * @param length The number of samples required to saturate the sliding window
  40504. */
  40505. function RollingAverage(length) {
  40506. this._samples = new Array(length);
  40507. this.reset();
  40508. }
  40509. /**
  40510. * Adds a sample to the sample set
  40511. * @param v The sample value
  40512. */
  40513. RollingAverage.prototype.add = function (v) {
  40514. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40515. var delta;
  40516. //we need to check if we've already wrapped round
  40517. if (this.isSaturated()) {
  40518. //remove bottom of stack from mean
  40519. var bottomValue = this._samples[this._pos];
  40520. delta = bottomValue - this.average;
  40521. this.average -= delta / (this._sampleCount - 1);
  40522. this._m2 -= delta * (bottomValue - this.average);
  40523. }
  40524. else {
  40525. this._sampleCount++;
  40526. }
  40527. //add new value to mean
  40528. delta = v - this.average;
  40529. this.average += delta / (this._sampleCount);
  40530. this._m2 += delta * (v - this.average);
  40531. //set the new variance
  40532. this.variance = this._m2 / (this._sampleCount - 1);
  40533. this._samples[this._pos] = v;
  40534. this._pos++;
  40535. this._pos %= this._samples.length; //positive wrap around
  40536. };
  40537. /**
  40538. * Returns previously added values or null if outside of history or outside the sliding window domain
  40539. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40540. * @return Value previously recorded with add() or null if outside of range
  40541. */
  40542. RollingAverage.prototype.history = function (i) {
  40543. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40544. return 0;
  40545. }
  40546. var i0 = this._wrapPosition(this._pos - 1.0);
  40547. return this._samples[this._wrapPosition(i0 - i)];
  40548. };
  40549. /**
  40550. * Returns true if enough samples have been taken to completely fill the sliding window
  40551. * @return true if sample-set saturated
  40552. */
  40553. RollingAverage.prototype.isSaturated = function () {
  40554. return this._sampleCount >= this._samples.length;
  40555. };
  40556. /**
  40557. * Resets the rolling average (equivalent to 0 samples taken so far)
  40558. */
  40559. RollingAverage.prototype.reset = function () {
  40560. this.average = 0;
  40561. this.variance = 0;
  40562. this._sampleCount = 0;
  40563. this._pos = 0;
  40564. this._m2 = 0;
  40565. };
  40566. /**
  40567. * Wraps a value around the sample range boundaries
  40568. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40569. * @return Wrapped position in sample range
  40570. */
  40571. RollingAverage.prototype._wrapPosition = function (i) {
  40572. var max = this._samples.length;
  40573. return ((i % max) + max) % max;
  40574. };
  40575. return RollingAverage;
  40576. }());
  40577. BABYLON.RollingAverage = RollingAverage;
  40578. })(BABYLON || (BABYLON = {}));
  40579. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40580. var BABYLON;
  40581. (function (BABYLON) {
  40582. /**
  40583. * "Static Class" containing the most commonly used helper while dealing with material for
  40584. * rendering purpose.
  40585. *
  40586. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40587. *
  40588. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40589. */
  40590. var MaterialHelper = /** @class */ (function () {
  40591. function MaterialHelper() {
  40592. }
  40593. /**
  40594. * Bind the current view position to an effect.
  40595. * @param effect The effect to be bound
  40596. * @param scene The scene the eyes position is used from
  40597. */
  40598. MaterialHelper.BindEyePosition = function (effect, scene) {
  40599. if (scene._forcedViewPosition) {
  40600. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40601. return;
  40602. }
  40603. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40604. };
  40605. /**
  40606. * Helps preparing the defines values about the UVs in used in the effect.
  40607. * UVs are shared as much as we can accross chanels in the shaders.
  40608. * @param texture The texture we are preparing the UVs for
  40609. * @param defines The defines to update
  40610. * @param key The chanel key "diffuse", "specular"... used in the shader
  40611. */
  40612. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40613. defines._needUVs = true;
  40614. defines[key] = true;
  40615. if (texture.getTextureMatrix().isIdentity(true)) {
  40616. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40617. if (texture.coordinatesIndex === 0) {
  40618. defines["MAINUV1"] = true;
  40619. }
  40620. else {
  40621. defines["MAINUV2"] = true;
  40622. }
  40623. }
  40624. else {
  40625. defines[key + "DIRECTUV"] = 0;
  40626. }
  40627. };
  40628. /**
  40629. * Binds a texture matrix value to its corrsponding uniform
  40630. * @param texture The texture to bind the matrix for
  40631. * @param uniformBuffer The uniform buffer receivin the data
  40632. * @param key The chanel key "diffuse", "specular"... used in the shader
  40633. */
  40634. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40635. var matrix = texture.getTextureMatrix();
  40636. if (!matrix.isIdentity(true)) {
  40637. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40638. }
  40639. };
  40640. /**
  40641. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40642. * @param mesh defines the current mesh
  40643. * @param scene defines the current scene
  40644. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40645. * @param pointsCloud defines if point cloud rendering has to be turned on
  40646. * @param fogEnabled defines if fog has to be turned on
  40647. * @param alphaTest defines if alpha testing has to be turned on
  40648. * @param defines defines the current list of defines
  40649. */
  40650. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40651. if (defines._areMiscDirty) {
  40652. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40653. defines["POINTSIZE"] = pointsCloud;
  40654. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40655. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40656. defines["ALPHATEST"] = alphaTest;
  40657. }
  40658. };
  40659. /**
  40660. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40661. * @param scene defines the current scene
  40662. * @param engine defines the current engine
  40663. * @param defines specifies the list of active defines
  40664. * @param useInstances defines if instances have to be turned on
  40665. * @param useClipPlane defines if clip plane have to be turned on
  40666. */
  40667. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40668. if (useClipPlane === void 0) { useClipPlane = null; }
  40669. var changed = false;
  40670. if (useClipPlane == null) {
  40671. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40672. }
  40673. if (defines["CLIPPLANE"] !== useClipPlane) {
  40674. defines["CLIPPLANE"] = useClipPlane;
  40675. changed = true;
  40676. }
  40677. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40678. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40679. changed = true;
  40680. }
  40681. if (defines["INSTANCES"] !== useInstances) {
  40682. defines["INSTANCES"] = useInstances;
  40683. changed = true;
  40684. }
  40685. if (changed) {
  40686. defines.markAsUnprocessed();
  40687. }
  40688. };
  40689. /**
  40690. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40691. * @param mesh The mesh containing the geometry data we will draw
  40692. * @param defines The defines to update
  40693. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40694. * @param useBones Precise whether bones should be used or not (override mesh info)
  40695. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40696. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40697. * @returns false if defines are considered not dirty and have not been checked
  40698. */
  40699. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40700. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40701. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40702. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40703. return false;
  40704. }
  40705. defines._normals = defines._needNormals;
  40706. defines._uvs = defines._needUVs;
  40707. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40708. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40709. defines["TANGENT"] = true;
  40710. }
  40711. if (defines._needUVs) {
  40712. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40713. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40714. }
  40715. else {
  40716. defines["UV1"] = false;
  40717. defines["UV2"] = false;
  40718. }
  40719. if (useVertexColor) {
  40720. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40721. defines["VERTEXCOLOR"] = hasVertexColors;
  40722. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40723. }
  40724. if (useBones) {
  40725. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40726. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40727. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40728. }
  40729. else {
  40730. defines["NUM_BONE_INFLUENCERS"] = 0;
  40731. defines["BonesPerMesh"] = 0;
  40732. }
  40733. }
  40734. if (useMorphTargets) {
  40735. var manager = mesh.morphTargetManager;
  40736. if (manager) {
  40737. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40738. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40739. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40740. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40741. }
  40742. else {
  40743. defines["MORPHTARGETS_TANGENT"] = false;
  40744. defines["MORPHTARGETS_NORMAL"] = false;
  40745. defines["MORPHTARGETS"] = false;
  40746. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40747. }
  40748. }
  40749. return true;
  40750. };
  40751. /**
  40752. * Prepares the defines related to the light information passed in parameter
  40753. * @param scene The scene we are intending to draw
  40754. * @param mesh The mesh the effect is compiling for
  40755. * @param defines The defines to update
  40756. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40757. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40758. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40759. * @returns true if normals will be required for the rest of the effect
  40760. */
  40761. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40762. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40763. if (disableLighting === void 0) { disableLighting = false; }
  40764. if (!defines._areLightsDirty) {
  40765. return defines._needNormals;
  40766. }
  40767. var lightIndex = 0;
  40768. var needNormals = false;
  40769. var needRebuild = false;
  40770. var lightmapMode = false;
  40771. var shadowEnabled = false;
  40772. var specularEnabled = false;
  40773. if (scene.lightsEnabled && !disableLighting) {
  40774. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40775. var light = _a[_i];
  40776. needNormals = true;
  40777. if (defines["LIGHT" + lightIndex] === undefined) {
  40778. needRebuild = true;
  40779. }
  40780. defines["LIGHT" + lightIndex] = true;
  40781. defines["SPOTLIGHT" + lightIndex] = false;
  40782. defines["HEMILIGHT" + lightIndex] = false;
  40783. defines["POINTLIGHT" + lightIndex] = false;
  40784. defines["DIRLIGHT" + lightIndex] = false;
  40785. light.prepareLightSpecificDefines(defines, lightIndex);
  40786. // Specular
  40787. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40788. specularEnabled = true;
  40789. }
  40790. // Shadows
  40791. defines["SHADOW" + lightIndex] = false;
  40792. defines["SHADOWPCF" + lightIndex] = false;
  40793. defines["SHADOWPCSS" + lightIndex] = false;
  40794. defines["SHADOWPOISSON" + lightIndex] = false;
  40795. defines["SHADOWESM" + lightIndex] = false;
  40796. defines["SHADOWCUBE" + lightIndex] = false;
  40797. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40798. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40799. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40800. var shadowGenerator = light.getShadowGenerator();
  40801. if (shadowGenerator) {
  40802. var shadowMap = shadowGenerator.getShadowMap();
  40803. if (shadowMap) {
  40804. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40805. shadowEnabled = true;
  40806. shadowGenerator.prepareDefines(defines, lightIndex);
  40807. }
  40808. }
  40809. }
  40810. }
  40811. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40812. lightmapMode = true;
  40813. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40814. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40815. }
  40816. else {
  40817. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40818. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40819. }
  40820. lightIndex++;
  40821. if (lightIndex === maxSimultaneousLights)
  40822. break;
  40823. }
  40824. }
  40825. defines["SPECULARTERM"] = specularEnabled;
  40826. defines["SHADOWS"] = shadowEnabled;
  40827. // Resetting all other lights if any
  40828. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40829. if (defines["LIGHT" + index] !== undefined) {
  40830. defines["LIGHT" + index] = false;
  40831. defines["HEMILIGHT" + lightIndex] = false;
  40832. defines["POINTLIGHT" + lightIndex] = false;
  40833. defines["DIRLIGHT" + lightIndex] = false;
  40834. defines["SPOTLIGHT" + lightIndex] = false;
  40835. defines["SHADOW" + lightIndex] = false;
  40836. }
  40837. }
  40838. var caps = scene.getEngine().getCaps();
  40839. if (defines["SHADOWFLOAT"] === undefined) {
  40840. needRebuild = true;
  40841. }
  40842. defines["SHADOWFLOAT"] = shadowEnabled &&
  40843. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40844. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40845. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40846. if (needRebuild) {
  40847. defines.rebuild();
  40848. }
  40849. return needNormals;
  40850. };
  40851. /**
  40852. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40853. * that won t be acctive due to defines being turned off.
  40854. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40855. * @param samplersList The samplers list
  40856. * @param defines The defines helping in the list generation
  40857. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40858. */
  40859. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40860. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40861. var uniformsList;
  40862. var uniformBuffersList = null;
  40863. if (uniformsListOrOptions.uniformsNames) {
  40864. var options = uniformsListOrOptions;
  40865. uniformsList = options.uniformsNames;
  40866. uniformBuffersList = options.uniformBuffersNames;
  40867. samplersList = options.samplers;
  40868. defines = options.defines;
  40869. maxSimultaneousLights = options.maxSimultaneousLights;
  40870. }
  40871. else {
  40872. uniformsList = uniformsListOrOptions;
  40873. if (!samplersList) {
  40874. samplersList = [];
  40875. }
  40876. }
  40877. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40878. if (!defines["LIGHT" + lightIndex]) {
  40879. break;
  40880. }
  40881. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40882. if (uniformBuffersList) {
  40883. uniformBuffersList.push("Light" + lightIndex);
  40884. }
  40885. samplersList.push("shadowSampler" + lightIndex);
  40886. samplersList.push("depthSampler" + lightIndex);
  40887. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40888. samplersList.push("projectionLightSampler" + lightIndex);
  40889. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40890. }
  40891. }
  40892. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40893. uniformsList.push("morphTargetInfluences");
  40894. }
  40895. };
  40896. /**
  40897. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40898. * @param defines The defines to update while falling back
  40899. * @param fallbacks The authorized effect fallbacks
  40900. * @param maxSimultaneousLights The maximum number of lights allowed
  40901. * @param rank the current rank of the Effect
  40902. * @returns The newly affected rank
  40903. */
  40904. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40905. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40906. if (rank === void 0) { rank = 0; }
  40907. var lightFallbackRank = 0;
  40908. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40909. if (!defines["LIGHT" + lightIndex]) {
  40910. break;
  40911. }
  40912. if (lightIndex > 0) {
  40913. lightFallbackRank = rank + lightIndex;
  40914. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40915. }
  40916. if (!defines["SHADOWS"]) {
  40917. if (defines["SHADOW" + lightIndex]) {
  40918. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40919. }
  40920. if (defines["SHADOWPCF" + lightIndex]) {
  40921. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40922. }
  40923. if (defines["SHADOWPCSS" + lightIndex]) {
  40924. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40925. }
  40926. if (defines["SHADOWPOISSON" + lightIndex]) {
  40927. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40928. }
  40929. if (defines["SHADOWESM" + lightIndex]) {
  40930. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40931. }
  40932. }
  40933. }
  40934. return lightFallbackRank++;
  40935. };
  40936. /**
  40937. * Prepares the list of attributes required for morph targets according to the effect defines.
  40938. * @param attribs The current list of supported attribs
  40939. * @param mesh The mesh to prepare the morph targets attributes for
  40940. * @param defines The current Defines of the effect
  40941. */
  40942. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40943. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40944. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40945. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40946. var manager = mesh.morphTargetManager;
  40947. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40948. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40949. for (var index = 0; index < influencers; index++) {
  40950. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40951. if (normal) {
  40952. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40953. }
  40954. if (tangent) {
  40955. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40956. }
  40957. if (attribs.length > maxAttributesCount) {
  40958. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  40959. }
  40960. }
  40961. }
  40962. };
  40963. /**
  40964. * Prepares the list of attributes required for bones according to the effect defines.
  40965. * @param attribs The current list of supported attribs
  40966. * @param mesh The mesh to prepare the bones attributes for
  40967. * @param defines The current Defines of the effect
  40968. * @param fallbacks The current efffect fallback strategy
  40969. */
  40970. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  40971. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  40972. fallbacks.addCPUSkinningFallback(0, mesh);
  40973. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40974. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40975. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  40976. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40977. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40978. }
  40979. }
  40980. };
  40981. /**
  40982. * Prepares the list of attributes required for instances according to the effect defines.
  40983. * @param attribs The current list of supported attribs
  40984. * @param defines The current Defines of the effect
  40985. */
  40986. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  40987. if (defines["INSTANCES"]) {
  40988. attribs.push("world0");
  40989. attribs.push("world1");
  40990. attribs.push("world2");
  40991. attribs.push("world3");
  40992. }
  40993. };
  40994. /**
  40995. * Binds the light shadow information to the effect for the given mesh.
  40996. * @param light The light containing the generator
  40997. * @param scene The scene the lights belongs to
  40998. * @param mesh The mesh we are binding the information to render
  40999. * @param lightIndex The light index in the effect used to render the mesh
  41000. * @param effect The effect we are binding the data to
  41001. */
  41002. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41003. if (light.shadowEnabled && mesh.receiveShadows) {
  41004. var shadowGenerator = light.getShadowGenerator();
  41005. if (shadowGenerator) {
  41006. shadowGenerator.bindShadowLight(lightIndex, effect);
  41007. }
  41008. }
  41009. };
  41010. /**
  41011. * Binds the light information to the effect.
  41012. * @param light The light containing the generator
  41013. * @param effect The effect we are binding the data to
  41014. * @param lightIndex The light index in the effect used to render
  41015. */
  41016. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41017. light.transferToEffect(effect, lightIndex + "");
  41018. };
  41019. /**
  41020. * Binds the lights information from the scene to the effect for the given mesh.
  41021. * @param scene The scene the lights belongs to
  41022. * @param mesh The mesh we are binding the information to render
  41023. * @param effect The effect we are binding the data to
  41024. * @param defines The generated defines for the effect
  41025. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41026. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41027. */
  41028. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41029. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41030. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41031. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41032. for (var i = 0; i < len; i++) {
  41033. var light = mesh._lightSources[i];
  41034. var iAsString = i.toString();
  41035. var scaledIntensity = light.getScaledIntensity();
  41036. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41037. MaterialHelper.BindLightProperties(light, effect, i);
  41038. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41039. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41040. if (defines["SPECULARTERM"]) {
  41041. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41042. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41043. }
  41044. // Shadows
  41045. if (scene.shadowsEnabled) {
  41046. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41047. }
  41048. light._uniformBuffer.update();
  41049. }
  41050. };
  41051. /**
  41052. * Binds the fog information from the scene to the effect for the given mesh.
  41053. * @param scene The scene the lights belongs to
  41054. * @param mesh The mesh we are binding the information to render
  41055. * @param effect The effect we are binding the data to
  41056. */
  41057. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41058. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41059. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41060. effect.setColor3("vFogColor", scene.fogColor);
  41061. }
  41062. };
  41063. /**
  41064. * Binds the bones information from the mesh to the effect.
  41065. * @param mesh The mesh we are binding the information to render
  41066. * @param effect The effect we are binding the data to
  41067. */
  41068. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41069. if (!effect || !mesh) {
  41070. return;
  41071. }
  41072. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41073. mesh.computeBonesUsingShaders = false;
  41074. }
  41075. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41076. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41077. if (matrices) {
  41078. effect.setMatrices("mBones", matrices);
  41079. }
  41080. }
  41081. };
  41082. /**
  41083. * Binds the morph targets information from the mesh to the effect.
  41084. * @param abstractMesh The mesh we are binding the information to render
  41085. * @param effect The effect we are binding the data to
  41086. */
  41087. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41088. var manager = abstractMesh.morphTargetManager;
  41089. if (!abstractMesh || !manager) {
  41090. return;
  41091. }
  41092. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41093. };
  41094. /**
  41095. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41096. * @param defines The generated defines used in the effect
  41097. * @param effect The effect we are binding the data to
  41098. * @param scene The scene we are willing to render with logarithmic scale for
  41099. */
  41100. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41101. if (defines["LOGARITHMICDEPTH"]) {
  41102. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41103. }
  41104. };
  41105. /**
  41106. * Binds the clip plane information from the scene to the effect.
  41107. * @param scene The scene the clip plane information are extracted from
  41108. * @param effect The effect we are binding the data to
  41109. */
  41110. MaterialHelper.BindClipPlane = function (effect, scene) {
  41111. if (scene.clipPlane) {
  41112. var clipPlane = scene.clipPlane;
  41113. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41114. }
  41115. };
  41116. return MaterialHelper;
  41117. }());
  41118. BABYLON.MaterialHelper = MaterialHelper;
  41119. })(BABYLON || (BABYLON = {}));
  41120. //# sourceMappingURL=babylon.materialHelper.js.map
  41121. var BABYLON;
  41122. (function (BABYLON) {
  41123. var PushMaterial = /** @class */ (function (_super) {
  41124. __extends(PushMaterial, _super);
  41125. function PushMaterial(name, scene) {
  41126. var _this = _super.call(this, name, scene) || this;
  41127. _this._normalMatrix = new BABYLON.Matrix();
  41128. _this.storeEffectOnSubMeshes = true;
  41129. return _this;
  41130. }
  41131. PushMaterial.prototype.getEffect = function () {
  41132. return this._activeEffect;
  41133. };
  41134. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41135. if (!mesh) {
  41136. return false;
  41137. }
  41138. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41139. return true;
  41140. }
  41141. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41142. };
  41143. /**
  41144. * Binds the given world matrix to the active effect
  41145. *
  41146. * @param world the matrix to bind
  41147. */
  41148. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41149. this._activeEffect.setMatrix("world", world);
  41150. };
  41151. /**
  41152. * Binds the given normal matrix to the active effect
  41153. *
  41154. * @param normalMatrix the matrix to bind
  41155. */
  41156. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41157. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41158. };
  41159. PushMaterial.prototype.bind = function (world, mesh) {
  41160. if (!mesh) {
  41161. return;
  41162. }
  41163. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41164. };
  41165. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41166. if (effect === void 0) { effect = null; }
  41167. _super.prototype._afterBind.call(this, mesh);
  41168. this.getScene()._cachedEffect = effect;
  41169. };
  41170. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41171. if (visibility === void 0) { visibility = 1; }
  41172. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41173. };
  41174. return PushMaterial;
  41175. }(BABYLON.Material));
  41176. BABYLON.PushMaterial = PushMaterial;
  41177. })(BABYLON || (BABYLON = {}));
  41178. //# sourceMappingURL=babylon.pushMaterial.js.map
  41179. var BABYLON;
  41180. (function (BABYLON) {
  41181. /** @hidden */
  41182. var StandardMaterialDefines = /** @class */ (function (_super) {
  41183. __extends(StandardMaterialDefines, _super);
  41184. function StandardMaterialDefines() {
  41185. var _this = _super.call(this) || this;
  41186. _this.MAINUV1 = false;
  41187. _this.MAINUV2 = false;
  41188. _this.DIFFUSE = false;
  41189. _this.DIFFUSEDIRECTUV = 0;
  41190. _this.AMBIENT = false;
  41191. _this.AMBIENTDIRECTUV = 0;
  41192. _this.OPACITY = false;
  41193. _this.OPACITYDIRECTUV = 0;
  41194. _this.OPACITYRGB = false;
  41195. _this.REFLECTION = false;
  41196. _this.EMISSIVE = false;
  41197. _this.EMISSIVEDIRECTUV = 0;
  41198. _this.SPECULAR = false;
  41199. _this.SPECULARDIRECTUV = 0;
  41200. _this.BUMP = false;
  41201. _this.BUMPDIRECTUV = 0;
  41202. _this.PARALLAX = false;
  41203. _this.PARALLAXOCCLUSION = false;
  41204. _this.SPECULAROVERALPHA = false;
  41205. _this.CLIPPLANE = false;
  41206. _this.ALPHATEST = false;
  41207. _this.DEPTHPREPASS = false;
  41208. _this.ALPHAFROMDIFFUSE = false;
  41209. _this.POINTSIZE = false;
  41210. _this.FOG = false;
  41211. _this.SPECULARTERM = false;
  41212. _this.DIFFUSEFRESNEL = false;
  41213. _this.OPACITYFRESNEL = false;
  41214. _this.REFLECTIONFRESNEL = false;
  41215. _this.REFRACTIONFRESNEL = false;
  41216. _this.EMISSIVEFRESNEL = false;
  41217. _this.FRESNEL = false;
  41218. _this.NORMAL = false;
  41219. _this.UV1 = false;
  41220. _this.UV2 = false;
  41221. _this.VERTEXCOLOR = false;
  41222. _this.VERTEXALPHA = false;
  41223. _this.NUM_BONE_INFLUENCERS = 0;
  41224. _this.BonesPerMesh = 0;
  41225. _this.INSTANCES = false;
  41226. _this.GLOSSINESS = false;
  41227. _this.ROUGHNESS = false;
  41228. _this.EMISSIVEASILLUMINATION = false;
  41229. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41230. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41231. _this.LIGHTMAP = false;
  41232. _this.LIGHTMAPDIRECTUV = 0;
  41233. _this.OBJECTSPACE_NORMALMAP = false;
  41234. _this.USELIGHTMAPASSHADOWMAP = false;
  41235. _this.REFLECTIONMAP_3D = false;
  41236. _this.REFLECTIONMAP_SPHERICAL = false;
  41237. _this.REFLECTIONMAP_PLANAR = false;
  41238. _this.REFLECTIONMAP_CUBIC = false;
  41239. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41240. _this.REFLECTIONMAP_PROJECTION = false;
  41241. _this.REFLECTIONMAP_SKYBOX = false;
  41242. _this.REFLECTIONMAP_EXPLICIT = false;
  41243. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41244. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41245. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41246. _this.INVERTCUBICMAP = false;
  41247. _this.LOGARITHMICDEPTH = false;
  41248. _this.REFRACTION = false;
  41249. _this.REFRACTIONMAP_3D = false;
  41250. _this.REFLECTIONOVERALPHA = false;
  41251. _this.TWOSIDEDLIGHTING = false;
  41252. _this.SHADOWFLOAT = false;
  41253. _this.MORPHTARGETS = false;
  41254. _this.MORPHTARGETS_NORMAL = false;
  41255. _this.MORPHTARGETS_TANGENT = false;
  41256. _this.NUM_MORPH_INFLUENCERS = 0;
  41257. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41258. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41259. _this.IMAGEPROCESSING = false;
  41260. _this.VIGNETTE = false;
  41261. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41262. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41263. _this.TONEMAPPING = false;
  41264. _this.CONTRAST = false;
  41265. _this.COLORCURVES = false;
  41266. _this.COLORGRADING = false;
  41267. _this.COLORGRADING3D = false;
  41268. _this.SAMPLER3DGREENDEPTH = false;
  41269. _this.SAMPLER3DBGRMAP = false;
  41270. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41271. /**
  41272. * If the reflection texture on this material is in linear color space
  41273. * @hidden
  41274. */
  41275. _this.IS_REFLECTION_LINEAR = false;
  41276. /**
  41277. * If the refraction texture on this material is in linear color space
  41278. * @hidden
  41279. */
  41280. _this.IS_REFRACTION_LINEAR = false;
  41281. _this.EXPOSURE = false;
  41282. _this.rebuild();
  41283. return _this;
  41284. }
  41285. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41286. var modes = [
  41287. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41288. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41289. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41290. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41291. ];
  41292. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41293. var mode = modes_1[_i];
  41294. this[mode] = (mode === modeToEnable);
  41295. }
  41296. };
  41297. return StandardMaterialDefines;
  41298. }(BABYLON.MaterialDefines));
  41299. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41300. var StandardMaterial = /** @class */ (function (_super) {
  41301. __extends(StandardMaterial, _super);
  41302. function StandardMaterial(name, scene) {
  41303. var _this = _super.call(this, name, scene) || this;
  41304. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41305. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41306. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41307. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41308. _this.specularPower = 64;
  41309. _this._useAlphaFromDiffuseTexture = false;
  41310. _this._useEmissiveAsIllumination = false;
  41311. _this._linkEmissiveWithDiffuse = false;
  41312. _this._useSpecularOverAlpha = false;
  41313. _this._useReflectionOverAlpha = false;
  41314. _this._disableLighting = false;
  41315. _this._useObjectSpaceNormalMap = false;
  41316. _this._useParallax = false;
  41317. _this._useParallaxOcclusion = false;
  41318. _this.parallaxScaleBias = 0.05;
  41319. _this._roughness = 0;
  41320. _this.indexOfRefraction = 0.98;
  41321. _this.invertRefractionY = true;
  41322. /**
  41323. * Defines the alpha limits in alpha test mode
  41324. */
  41325. _this.alphaCutOff = 0.4;
  41326. _this._useLightmapAsShadowmap = false;
  41327. _this._useReflectionFresnelFromSpecular = false;
  41328. _this._useGlossinessFromSpecularMapAlpha = false;
  41329. _this._maxSimultaneousLights = 4;
  41330. /**
  41331. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41332. */
  41333. _this._invertNormalMapX = false;
  41334. /**
  41335. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41336. */
  41337. _this._invertNormalMapY = false;
  41338. /**
  41339. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41340. */
  41341. _this._twoSidedLighting = false;
  41342. _this._renderTargets = new BABYLON.SmartArray(16);
  41343. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41344. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41345. // Setup the default processing configuration to the scene.
  41346. _this._attachImageProcessingConfiguration(null);
  41347. _this.getRenderTargetTextures = function () {
  41348. _this._renderTargets.reset();
  41349. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41350. _this._renderTargets.push(_this._reflectionTexture);
  41351. }
  41352. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41353. _this._renderTargets.push(_this._refractionTexture);
  41354. }
  41355. return _this._renderTargets;
  41356. };
  41357. return _this;
  41358. }
  41359. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41360. /**
  41361. * Gets the image processing configuration used either in this material.
  41362. */
  41363. get: function () {
  41364. return this._imageProcessingConfiguration;
  41365. },
  41366. /**
  41367. * Sets the Default image processing configuration used either in the this material.
  41368. *
  41369. * If sets to null, the scene one is in use.
  41370. */
  41371. set: function (value) {
  41372. this._attachImageProcessingConfiguration(value);
  41373. // Ensure the effect will be rebuilt.
  41374. this._markAllSubMeshesAsTexturesDirty();
  41375. },
  41376. enumerable: true,
  41377. configurable: true
  41378. });
  41379. /**
  41380. * Attaches a new image processing configuration to the Standard Material.
  41381. * @param configuration
  41382. */
  41383. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41384. var _this = this;
  41385. if (configuration === this._imageProcessingConfiguration) {
  41386. return;
  41387. }
  41388. // Detaches observer.
  41389. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41390. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41391. }
  41392. // Pick the scene configuration if needed.
  41393. if (!configuration) {
  41394. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41395. }
  41396. else {
  41397. this._imageProcessingConfiguration = configuration;
  41398. }
  41399. // Attaches observer.
  41400. if (this._imageProcessingConfiguration) {
  41401. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41402. _this._markAllSubMeshesAsImageProcessingDirty();
  41403. });
  41404. }
  41405. };
  41406. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41407. /**
  41408. * Gets wether the color curves effect is enabled.
  41409. */
  41410. get: function () {
  41411. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41412. },
  41413. /**
  41414. * Sets wether the color curves effect is enabled.
  41415. */
  41416. set: function (value) {
  41417. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41418. },
  41419. enumerable: true,
  41420. configurable: true
  41421. });
  41422. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41423. /**
  41424. * Gets wether the color grading effect is enabled.
  41425. */
  41426. get: function () {
  41427. return this.imageProcessingConfiguration.colorGradingEnabled;
  41428. },
  41429. /**
  41430. * Gets wether the color grading effect is enabled.
  41431. */
  41432. set: function (value) {
  41433. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41434. },
  41435. enumerable: true,
  41436. configurable: true
  41437. });
  41438. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41439. /**
  41440. * Gets wether tonemapping is enabled or not.
  41441. */
  41442. get: function () {
  41443. return this._imageProcessingConfiguration.toneMappingEnabled;
  41444. },
  41445. /**
  41446. * Sets wether tonemapping is enabled or not
  41447. */
  41448. set: function (value) {
  41449. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41450. },
  41451. enumerable: true,
  41452. configurable: true
  41453. });
  41454. ;
  41455. ;
  41456. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41457. /**
  41458. * The camera exposure used on this material.
  41459. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41460. * This corresponds to a photographic exposure.
  41461. */
  41462. get: function () {
  41463. return this._imageProcessingConfiguration.exposure;
  41464. },
  41465. /**
  41466. * The camera exposure used on this material.
  41467. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41468. * This corresponds to a photographic exposure.
  41469. */
  41470. set: function (value) {
  41471. this._imageProcessingConfiguration.exposure = value;
  41472. },
  41473. enumerable: true,
  41474. configurable: true
  41475. });
  41476. ;
  41477. ;
  41478. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41479. /**
  41480. * Gets The camera contrast used on this material.
  41481. */
  41482. get: function () {
  41483. return this._imageProcessingConfiguration.contrast;
  41484. },
  41485. /**
  41486. * Sets The camera contrast used on this material.
  41487. */
  41488. set: function (value) {
  41489. this._imageProcessingConfiguration.contrast = value;
  41490. },
  41491. enumerable: true,
  41492. configurable: true
  41493. });
  41494. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41495. /**
  41496. * Gets the Color Grading 2D Lookup Texture.
  41497. */
  41498. get: function () {
  41499. return this._imageProcessingConfiguration.colorGradingTexture;
  41500. },
  41501. /**
  41502. * Sets the Color Grading 2D Lookup Texture.
  41503. */
  41504. set: function (value) {
  41505. this._imageProcessingConfiguration.colorGradingTexture = value;
  41506. },
  41507. enumerable: true,
  41508. configurable: true
  41509. });
  41510. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41511. /**
  41512. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41513. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41514. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  41515. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41516. */
  41517. get: function () {
  41518. return this._imageProcessingConfiguration.colorCurves;
  41519. },
  41520. /**
  41521. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41522. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41523. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  41524. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41525. */
  41526. set: function (value) {
  41527. this._imageProcessingConfiguration.colorCurves = value;
  41528. },
  41529. enumerable: true,
  41530. configurable: true
  41531. });
  41532. StandardMaterial.prototype.getClassName = function () {
  41533. return "StandardMaterial";
  41534. };
  41535. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41536. get: function () {
  41537. return this._useLogarithmicDepth;
  41538. },
  41539. set: function (value) {
  41540. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41541. this._markAllSubMeshesAsMiscDirty();
  41542. },
  41543. enumerable: true,
  41544. configurable: true
  41545. });
  41546. StandardMaterial.prototype.needAlphaBlending = function () {
  41547. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41548. };
  41549. StandardMaterial.prototype.needAlphaTesting = function () {
  41550. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41551. };
  41552. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41553. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41554. };
  41555. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41556. return this._diffuseTexture;
  41557. };
  41558. /**
  41559. * Child classes can use it to update shaders
  41560. */
  41561. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41562. if (useInstances === void 0) { useInstances = false; }
  41563. if (subMesh.effect && this.isFrozen) {
  41564. if (this._wasPreviouslyReady && subMesh.effect) {
  41565. return true;
  41566. }
  41567. }
  41568. if (!subMesh._materialDefines) {
  41569. subMesh._materialDefines = new StandardMaterialDefines();
  41570. }
  41571. var scene = this.getScene();
  41572. var defines = subMesh._materialDefines;
  41573. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41574. if (defines._renderId === scene.getRenderId()) {
  41575. return true;
  41576. }
  41577. }
  41578. var engine = scene.getEngine();
  41579. // Lights
  41580. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41581. // Textures
  41582. if (defines._areTexturesDirty) {
  41583. defines._needUVs = false;
  41584. defines.MAINUV1 = false;
  41585. defines.MAINUV2 = false;
  41586. if (scene.texturesEnabled) {
  41587. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41588. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41589. return false;
  41590. }
  41591. else {
  41592. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41593. }
  41594. }
  41595. else {
  41596. defines.DIFFUSE = false;
  41597. }
  41598. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41599. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41600. return false;
  41601. }
  41602. else {
  41603. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41604. }
  41605. }
  41606. else {
  41607. defines.AMBIENT = false;
  41608. }
  41609. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41610. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41611. return false;
  41612. }
  41613. else {
  41614. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41615. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41616. }
  41617. }
  41618. else {
  41619. defines.OPACITY = false;
  41620. }
  41621. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41622. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41623. return false;
  41624. }
  41625. else {
  41626. defines._needNormals = true;
  41627. defines.REFLECTION = true;
  41628. defines.ROUGHNESS = (this._roughness > 0);
  41629. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41630. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41631. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41632. switch (this._reflectionTexture.coordinatesMode) {
  41633. case BABYLON.Texture.EXPLICIT_MODE:
  41634. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41635. break;
  41636. case BABYLON.Texture.PLANAR_MODE:
  41637. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41638. break;
  41639. case BABYLON.Texture.PROJECTION_MODE:
  41640. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41641. break;
  41642. case BABYLON.Texture.SKYBOX_MODE:
  41643. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41644. break;
  41645. case BABYLON.Texture.SPHERICAL_MODE:
  41646. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41647. break;
  41648. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41649. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41650. break;
  41651. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41652. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41653. break;
  41654. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41655. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41656. break;
  41657. case BABYLON.Texture.CUBIC_MODE:
  41658. case BABYLON.Texture.INVCUBIC_MODE:
  41659. default:
  41660. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41661. break;
  41662. }
  41663. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41664. }
  41665. }
  41666. else {
  41667. defines.REFLECTION = false;
  41668. }
  41669. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41670. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41671. return false;
  41672. }
  41673. else {
  41674. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41675. }
  41676. }
  41677. else {
  41678. defines.EMISSIVE = false;
  41679. }
  41680. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41681. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41682. return false;
  41683. }
  41684. else {
  41685. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41686. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41687. }
  41688. }
  41689. else {
  41690. defines.LIGHTMAP = false;
  41691. }
  41692. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41693. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41694. return false;
  41695. }
  41696. else {
  41697. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41698. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41699. }
  41700. }
  41701. else {
  41702. defines.SPECULAR = false;
  41703. }
  41704. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41705. // Bump texure can not be not blocking.
  41706. if (!this._bumpTexture.isReady()) {
  41707. return false;
  41708. }
  41709. else {
  41710. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41711. defines.PARALLAX = this._useParallax;
  41712. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41713. }
  41714. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41715. }
  41716. else {
  41717. defines.BUMP = false;
  41718. }
  41719. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41720. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41721. return false;
  41722. }
  41723. else {
  41724. defines._needUVs = true;
  41725. defines.REFRACTION = true;
  41726. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41727. }
  41728. }
  41729. else {
  41730. defines.REFRACTION = false;
  41731. }
  41732. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41733. }
  41734. else {
  41735. defines.DIFFUSE = false;
  41736. defines.AMBIENT = false;
  41737. defines.OPACITY = false;
  41738. defines.REFLECTION = false;
  41739. defines.EMISSIVE = false;
  41740. defines.LIGHTMAP = false;
  41741. defines.BUMP = false;
  41742. defines.REFRACTION = false;
  41743. }
  41744. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41745. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41746. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41747. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41748. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41749. }
  41750. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41751. if (!this._imageProcessingConfiguration.isReady()) {
  41752. return false;
  41753. }
  41754. this._imageProcessingConfiguration.prepareDefines(defines);
  41755. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41756. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41757. }
  41758. if (defines._areFresnelDirty) {
  41759. if (StandardMaterial.FresnelEnabled) {
  41760. // Fresnel
  41761. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41762. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41763. this._reflectionFresnelParameters) {
  41764. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41765. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41766. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41767. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41768. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41769. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41770. defines._needNormals = true;
  41771. defines.FRESNEL = true;
  41772. }
  41773. }
  41774. else {
  41775. defines.FRESNEL = false;
  41776. }
  41777. }
  41778. // Misc.
  41779. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41780. // Attribs
  41781. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41782. // Values that need to be evaluated on every frame
  41783. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41784. // Get correct effect
  41785. if (defines.isDirty) {
  41786. defines.markAsProcessed();
  41787. scene.resetCachedMaterial();
  41788. // Fallbacks
  41789. var fallbacks = new BABYLON.EffectFallbacks();
  41790. if (defines.REFLECTION) {
  41791. fallbacks.addFallback(0, "REFLECTION");
  41792. }
  41793. if (defines.SPECULAR) {
  41794. fallbacks.addFallback(0, "SPECULAR");
  41795. }
  41796. if (defines.BUMP) {
  41797. fallbacks.addFallback(0, "BUMP");
  41798. }
  41799. if (defines.PARALLAX) {
  41800. fallbacks.addFallback(1, "PARALLAX");
  41801. }
  41802. if (defines.PARALLAXOCCLUSION) {
  41803. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41804. }
  41805. if (defines.SPECULAROVERALPHA) {
  41806. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41807. }
  41808. if (defines.FOG) {
  41809. fallbacks.addFallback(1, "FOG");
  41810. }
  41811. if (defines.POINTSIZE) {
  41812. fallbacks.addFallback(0, "POINTSIZE");
  41813. }
  41814. if (defines.LOGARITHMICDEPTH) {
  41815. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41816. }
  41817. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41818. if (defines.SPECULARTERM) {
  41819. fallbacks.addFallback(0, "SPECULARTERM");
  41820. }
  41821. if (defines.DIFFUSEFRESNEL) {
  41822. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41823. }
  41824. if (defines.OPACITYFRESNEL) {
  41825. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41826. }
  41827. if (defines.REFLECTIONFRESNEL) {
  41828. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41829. }
  41830. if (defines.EMISSIVEFRESNEL) {
  41831. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41832. }
  41833. if (defines.FRESNEL) {
  41834. fallbacks.addFallback(4, "FRESNEL");
  41835. }
  41836. //Attributes
  41837. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41838. if (defines.NORMAL) {
  41839. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41840. }
  41841. if (defines.UV1) {
  41842. attribs.push(BABYLON.VertexBuffer.UVKind);
  41843. }
  41844. if (defines.UV2) {
  41845. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41846. }
  41847. if (defines.VERTEXCOLOR) {
  41848. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41849. }
  41850. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41851. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41852. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41853. var shaderName = "default";
  41854. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41855. "vFogInfos", "vFogColor", "pointSize",
  41856. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41857. "mBones",
  41858. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41859. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41860. "vReflectionPosition", "vReflectionSize",
  41861. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41862. ];
  41863. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41864. var uniformBuffers = ["Material", "Scene"];
  41865. if (BABYLON.ImageProcessingConfiguration) {
  41866. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41867. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41868. }
  41869. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41870. uniformsNames: uniforms,
  41871. uniformBuffersNames: uniformBuffers,
  41872. samplers: samplers,
  41873. defines: defines,
  41874. maxSimultaneousLights: this._maxSimultaneousLights
  41875. });
  41876. if (this.customShaderNameResolve) {
  41877. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41878. }
  41879. var join = defines.toString();
  41880. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41881. attributes: attribs,
  41882. uniformsNames: uniforms,
  41883. uniformBuffersNames: uniformBuffers,
  41884. samplers: samplers,
  41885. defines: join,
  41886. fallbacks: fallbacks,
  41887. onCompiled: this.onCompiled,
  41888. onError: this.onError,
  41889. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41890. }, engine), defines);
  41891. this.buildUniformLayout();
  41892. }
  41893. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41894. return false;
  41895. }
  41896. defines._renderId = scene.getRenderId();
  41897. this._wasPreviouslyReady = true;
  41898. return true;
  41899. };
  41900. StandardMaterial.prototype.buildUniformLayout = function () {
  41901. // Order is important !
  41902. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41903. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41904. this._uniformBuffer.addUniform("opacityParts", 4);
  41905. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41906. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41907. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41908. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41909. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41910. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41911. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41912. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41913. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41914. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41915. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41916. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41917. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41918. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41919. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41920. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41921. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41922. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41923. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41924. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41925. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41926. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41927. this._uniformBuffer.addUniform("specularMatrix", 16);
  41928. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41929. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41930. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41931. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41932. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41933. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41934. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41935. this._uniformBuffer.addUniform("pointSize", 1);
  41936. this._uniformBuffer.create();
  41937. };
  41938. StandardMaterial.prototype.unbind = function () {
  41939. if (this._activeEffect) {
  41940. var needFlag = false;
  41941. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41942. this._activeEffect.setTexture("reflection2DSampler", null);
  41943. needFlag = true;
  41944. }
  41945. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41946. this._activeEffect.setTexture("refraction2DSampler", null);
  41947. needFlag = true;
  41948. }
  41949. if (needFlag) {
  41950. this._markAllSubMeshesAsTexturesDirty();
  41951. }
  41952. }
  41953. _super.prototype.unbind.call(this);
  41954. };
  41955. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41956. var scene = this.getScene();
  41957. var defines = subMesh._materialDefines;
  41958. if (!defines) {
  41959. return;
  41960. }
  41961. var effect = subMesh.effect;
  41962. if (!effect) {
  41963. return;
  41964. }
  41965. this._activeEffect = effect;
  41966. // Matrices
  41967. this.bindOnlyWorldMatrix(world);
  41968. // Normal Matrix
  41969. if (defines.OBJECTSPACE_NORMALMAP) {
  41970. world.toNormalMatrix(this._normalMatrix);
  41971. this.bindOnlyNormalMatrix(this._normalMatrix);
  41972. }
  41973. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41974. // Bones
  41975. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41976. if (mustRebind) {
  41977. this._uniformBuffer.bindToEffect(effect, "Material");
  41978. this.bindViewProjection(effect);
  41979. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41980. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41981. // Fresnel
  41982. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  41983. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  41984. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  41985. }
  41986. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  41987. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  41988. }
  41989. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  41990. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  41991. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  41992. }
  41993. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  41994. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  41995. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  41996. }
  41997. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  41998. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  41999. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42000. }
  42001. }
  42002. // Textures
  42003. if (scene.texturesEnabled) {
  42004. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42005. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42006. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42007. if (this._diffuseTexture.hasAlpha) {
  42008. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42009. }
  42010. }
  42011. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42012. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42013. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42014. }
  42015. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42016. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42017. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42018. }
  42019. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42020. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42021. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42022. if (this._reflectionTexture.boundingBoxSize) {
  42023. var cubeTexture = this._reflectionTexture;
  42024. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42025. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42026. }
  42027. }
  42028. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42029. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42030. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42031. }
  42032. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42033. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42034. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42035. }
  42036. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42037. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42038. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42039. }
  42040. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42041. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42042. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42043. if (scene._mirroredCameraPosition) {
  42044. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42045. }
  42046. else {
  42047. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42048. }
  42049. }
  42050. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42051. var depth = 1.0;
  42052. if (!this._refractionTexture.isCube) {
  42053. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42054. if (this._refractionTexture.depth) {
  42055. depth = this._refractionTexture.depth;
  42056. }
  42057. }
  42058. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42059. }
  42060. }
  42061. // Point size
  42062. if (this.pointsCloud) {
  42063. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42064. }
  42065. if (defines.SPECULARTERM) {
  42066. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42067. }
  42068. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42069. // Diffuse
  42070. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42071. }
  42072. // Textures
  42073. if (scene.texturesEnabled) {
  42074. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42075. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42076. }
  42077. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42078. effect.setTexture("ambientSampler", this._ambientTexture);
  42079. }
  42080. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42081. effect.setTexture("opacitySampler", this._opacityTexture);
  42082. }
  42083. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42084. if (this._reflectionTexture.isCube) {
  42085. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42086. }
  42087. else {
  42088. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42089. }
  42090. }
  42091. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42092. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42093. }
  42094. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42095. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42096. }
  42097. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42098. effect.setTexture("specularSampler", this._specularTexture);
  42099. }
  42100. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42101. effect.setTexture("bumpSampler", this._bumpTexture);
  42102. }
  42103. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42104. var depth = 1.0;
  42105. if (this._refractionTexture.isCube) {
  42106. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42107. }
  42108. else {
  42109. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42110. }
  42111. }
  42112. }
  42113. // Clip plane
  42114. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42115. // Colors
  42116. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42117. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42118. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42119. }
  42120. if (mustRebind || !this.isFrozen) {
  42121. // Lights
  42122. if (scene.lightsEnabled && !this._disableLighting) {
  42123. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42124. }
  42125. // View
  42126. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42127. this.bindView(effect);
  42128. }
  42129. // Fog
  42130. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42131. // Morph targets
  42132. if (defines.NUM_MORPH_INFLUENCERS) {
  42133. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42134. }
  42135. // Log. depth
  42136. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42137. // image processing
  42138. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42139. this._imageProcessingConfiguration.bind(this._activeEffect);
  42140. }
  42141. }
  42142. this._uniformBuffer.update();
  42143. this._afterBind(mesh, this._activeEffect);
  42144. };
  42145. StandardMaterial.prototype.getAnimatables = function () {
  42146. var results = [];
  42147. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42148. results.push(this._diffuseTexture);
  42149. }
  42150. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42151. results.push(this._ambientTexture);
  42152. }
  42153. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42154. results.push(this._opacityTexture);
  42155. }
  42156. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42157. results.push(this._reflectionTexture);
  42158. }
  42159. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42160. results.push(this._emissiveTexture);
  42161. }
  42162. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42163. results.push(this._specularTexture);
  42164. }
  42165. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42166. results.push(this._bumpTexture);
  42167. }
  42168. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42169. results.push(this._lightmapTexture);
  42170. }
  42171. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42172. results.push(this._refractionTexture);
  42173. }
  42174. return results;
  42175. };
  42176. StandardMaterial.prototype.getActiveTextures = function () {
  42177. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42178. if (this._diffuseTexture) {
  42179. activeTextures.push(this._diffuseTexture);
  42180. }
  42181. if (this._ambientTexture) {
  42182. activeTextures.push(this._ambientTexture);
  42183. }
  42184. if (this._opacityTexture) {
  42185. activeTextures.push(this._opacityTexture);
  42186. }
  42187. if (this._reflectionTexture) {
  42188. activeTextures.push(this._reflectionTexture);
  42189. }
  42190. if (this._emissiveTexture) {
  42191. activeTextures.push(this._emissiveTexture);
  42192. }
  42193. if (this._specularTexture) {
  42194. activeTextures.push(this._specularTexture);
  42195. }
  42196. if (this._bumpTexture) {
  42197. activeTextures.push(this._bumpTexture);
  42198. }
  42199. if (this._lightmapTexture) {
  42200. activeTextures.push(this._lightmapTexture);
  42201. }
  42202. if (this._refractionTexture) {
  42203. activeTextures.push(this._refractionTexture);
  42204. }
  42205. return activeTextures;
  42206. };
  42207. StandardMaterial.prototype.hasTexture = function (texture) {
  42208. if (_super.prototype.hasTexture.call(this, texture)) {
  42209. return true;
  42210. }
  42211. if (this._diffuseTexture === texture) {
  42212. return true;
  42213. }
  42214. if (this._ambientTexture === texture) {
  42215. return true;
  42216. }
  42217. if (this._opacityTexture === texture) {
  42218. return true;
  42219. }
  42220. if (this._reflectionTexture === texture) {
  42221. return true;
  42222. }
  42223. if (this._emissiveTexture === texture) {
  42224. return true;
  42225. }
  42226. if (this._specularTexture === texture) {
  42227. return true;
  42228. }
  42229. if (this._bumpTexture === texture) {
  42230. return true;
  42231. }
  42232. if (this._lightmapTexture === texture) {
  42233. return true;
  42234. }
  42235. if (this._refractionTexture === texture) {
  42236. return true;
  42237. }
  42238. return false;
  42239. };
  42240. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42241. if (forceDisposeTextures) {
  42242. if (this._diffuseTexture) {
  42243. this._diffuseTexture.dispose();
  42244. }
  42245. if (this._ambientTexture) {
  42246. this._ambientTexture.dispose();
  42247. }
  42248. if (this._opacityTexture) {
  42249. this._opacityTexture.dispose();
  42250. }
  42251. if (this._reflectionTexture) {
  42252. this._reflectionTexture.dispose();
  42253. }
  42254. if (this._emissiveTexture) {
  42255. this._emissiveTexture.dispose();
  42256. }
  42257. if (this._specularTexture) {
  42258. this._specularTexture.dispose();
  42259. }
  42260. if (this._bumpTexture) {
  42261. this._bumpTexture.dispose();
  42262. }
  42263. if (this._lightmapTexture) {
  42264. this._lightmapTexture.dispose();
  42265. }
  42266. if (this._refractionTexture) {
  42267. this._refractionTexture.dispose();
  42268. }
  42269. }
  42270. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42271. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42272. }
  42273. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42274. };
  42275. StandardMaterial.prototype.clone = function (name) {
  42276. var _this = this;
  42277. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42278. result.name = name;
  42279. result.id = name;
  42280. return result;
  42281. };
  42282. StandardMaterial.prototype.serialize = function () {
  42283. return BABYLON.SerializationHelper.Serialize(this);
  42284. };
  42285. // Statics
  42286. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42287. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42288. };
  42289. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42290. get: function () {
  42291. return StandardMaterial._DiffuseTextureEnabled;
  42292. },
  42293. set: function (value) {
  42294. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42295. return;
  42296. }
  42297. StandardMaterial._DiffuseTextureEnabled = value;
  42298. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42299. },
  42300. enumerable: true,
  42301. configurable: true
  42302. });
  42303. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42304. get: function () {
  42305. return StandardMaterial._AmbientTextureEnabled;
  42306. },
  42307. set: function (value) {
  42308. if (StandardMaterial._AmbientTextureEnabled === value) {
  42309. return;
  42310. }
  42311. StandardMaterial._AmbientTextureEnabled = value;
  42312. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42313. },
  42314. enumerable: true,
  42315. configurable: true
  42316. });
  42317. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42318. get: function () {
  42319. return StandardMaterial._OpacityTextureEnabled;
  42320. },
  42321. set: function (value) {
  42322. if (StandardMaterial._OpacityTextureEnabled === value) {
  42323. return;
  42324. }
  42325. StandardMaterial._OpacityTextureEnabled = value;
  42326. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42327. },
  42328. enumerable: true,
  42329. configurable: true
  42330. });
  42331. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42332. get: function () {
  42333. return StandardMaterial._ReflectionTextureEnabled;
  42334. },
  42335. set: function (value) {
  42336. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42337. return;
  42338. }
  42339. StandardMaterial._ReflectionTextureEnabled = value;
  42340. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42341. },
  42342. enumerable: true,
  42343. configurable: true
  42344. });
  42345. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42346. get: function () {
  42347. return StandardMaterial._EmissiveTextureEnabled;
  42348. },
  42349. set: function (value) {
  42350. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42351. return;
  42352. }
  42353. StandardMaterial._EmissiveTextureEnabled = value;
  42354. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42355. },
  42356. enumerable: true,
  42357. configurable: true
  42358. });
  42359. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42360. get: function () {
  42361. return StandardMaterial._SpecularTextureEnabled;
  42362. },
  42363. set: function (value) {
  42364. if (StandardMaterial._SpecularTextureEnabled === value) {
  42365. return;
  42366. }
  42367. StandardMaterial._SpecularTextureEnabled = value;
  42368. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42369. },
  42370. enumerable: true,
  42371. configurable: true
  42372. });
  42373. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42374. get: function () {
  42375. return StandardMaterial._BumpTextureEnabled;
  42376. },
  42377. set: function (value) {
  42378. if (StandardMaterial._BumpTextureEnabled === value) {
  42379. return;
  42380. }
  42381. StandardMaterial._BumpTextureEnabled = value;
  42382. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42383. },
  42384. enumerable: true,
  42385. configurable: true
  42386. });
  42387. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42388. get: function () {
  42389. return StandardMaterial._LightmapTextureEnabled;
  42390. },
  42391. set: function (value) {
  42392. if (StandardMaterial._LightmapTextureEnabled === value) {
  42393. return;
  42394. }
  42395. StandardMaterial._LightmapTextureEnabled = value;
  42396. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42397. },
  42398. enumerable: true,
  42399. configurable: true
  42400. });
  42401. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42402. get: function () {
  42403. return StandardMaterial._RefractionTextureEnabled;
  42404. },
  42405. set: function (value) {
  42406. if (StandardMaterial._RefractionTextureEnabled === value) {
  42407. return;
  42408. }
  42409. StandardMaterial._RefractionTextureEnabled = value;
  42410. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42411. },
  42412. enumerable: true,
  42413. configurable: true
  42414. });
  42415. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42416. get: function () {
  42417. return StandardMaterial._ColorGradingTextureEnabled;
  42418. },
  42419. set: function (value) {
  42420. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42421. return;
  42422. }
  42423. StandardMaterial._ColorGradingTextureEnabled = value;
  42424. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42425. },
  42426. enumerable: true,
  42427. configurable: true
  42428. });
  42429. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42430. get: function () {
  42431. return StandardMaterial._FresnelEnabled;
  42432. },
  42433. set: function (value) {
  42434. if (StandardMaterial._FresnelEnabled === value) {
  42435. return;
  42436. }
  42437. StandardMaterial._FresnelEnabled = value;
  42438. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42439. },
  42440. enumerable: true,
  42441. configurable: true
  42442. });
  42443. // Flags used to enable or disable a type of texture for all Standard Materials
  42444. StandardMaterial._DiffuseTextureEnabled = true;
  42445. StandardMaterial._AmbientTextureEnabled = true;
  42446. StandardMaterial._OpacityTextureEnabled = true;
  42447. StandardMaterial._ReflectionTextureEnabled = true;
  42448. StandardMaterial._EmissiveTextureEnabled = true;
  42449. StandardMaterial._SpecularTextureEnabled = true;
  42450. StandardMaterial._BumpTextureEnabled = true;
  42451. StandardMaterial._LightmapTextureEnabled = true;
  42452. StandardMaterial._RefractionTextureEnabled = true;
  42453. StandardMaterial._ColorGradingTextureEnabled = true;
  42454. StandardMaterial._FresnelEnabled = true;
  42455. __decorate([
  42456. BABYLON.serializeAsTexture("diffuseTexture")
  42457. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42458. __decorate([
  42459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42460. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42461. __decorate([
  42462. BABYLON.serializeAsTexture("ambientTexture")
  42463. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42464. __decorate([
  42465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42466. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42467. __decorate([
  42468. BABYLON.serializeAsTexture("opacityTexture")
  42469. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42470. __decorate([
  42471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42472. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42473. __decorate([
  42474. BABYLON.serializeAsTexture("reflectionTexture")
  42475. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42476. __decorate([
  42477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42478. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42479. __decorate([
  42480. BABYLON.serializeAsTexture("emissiveTexture")
  42481. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42482. __decorate([
  42483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42484. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42485. __decorate([
  42486. BABYLON.serializeAsTexture("specularTexture")
  42487. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42488. __decorate([
  42489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42490. ], StandardMaterial.prototype, "specularTexture", void 0);
  42491. __decorate([
  42492. BABYLON.serializeAsTexture("bumpTexture")
  42493. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42494. __decorate([
  42495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42496. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42497. __decorate([
  42498. BABYLON.serializeAsTexture("lightmapTexture")
  42499. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42500. __decorate([
  42501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42502. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42503. __decorate([
  42504. BABYLON.serializeAsTexture("refractionTexture")
  42505. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42506. __decorate([
  42507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42508. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42509. __decorate([
  42510. BABYLON.serializeAsColor3("ambient")
  42511. ], StandardMaterial.prototype, "ambientColor", void 0);
  42512. __decorate([
  42513. BABYLON.serializeAsColor3("diffuse")
  42514. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42515. __decorate([
  42516. BABYLON.serializeAsColor3("specular")
  42517. ], StandardMaterial.prototype, "specularColor", void 0);
  42518. __decorate([
  42519. BABYLON.serializeAsColor3("emissive")
  42520. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42521. __decorate([
  42522. BABYLON.serialize()
  42523. ], StandardMaterial.prototype, "specularPower", void 0);
  42524. __decorate([
  42525. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42526. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42527. __decorate([
  42528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42529. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42530. __decorate([
  42531. BABYLON.serialize("useEmissiveAsIllumination")
  42532. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42533. __decorate([
  42534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42535. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42536. __decorate([
  42537. BABYLON.serialize("linkEmissiveWithDiffuse")
  42538. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42539. __decorate([
  42540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42541. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42542. __decorate([
  42543. BABYLON.serialize("useSpecularOverAlpha")
  42544. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42545. __decorate([
  42546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42547. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42548. __decorate([
  42549. BABYLON.serialize("useReflectionOverAlpha")
  42550. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42551. __decorate([
  42552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42553. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42554. __decorate([
  42555. BABYLON.serialize("disableLighting")
  42556. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42557. __decorate([
  42558. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42559. ], StandardMaterial.prototype, "disableLighting", void 0);
  42560. __decorate([
  42561. BABYLON.serialize("useObjectSpaceNormalMap")
  42562. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42563. __decorate([
  42564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42565. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42566. __decorate([
  42567. BABYLON.serialize("useParallax")
  42568. ], StandardMaterial.prototype, "_useParallax", void 0);
  42569. __decorate([
  42570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42571. ], StandardMaterial.prototype, "useParallax", void 0);
  42572. __decorate([
  42573. BABYLON.serialize("useParallaxOcclusion")
  42574. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42575. __decorate([
  42576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42577. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42578. __decorate([
  42579. BABYLON.serialize()
  42580. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42581. __decorate([
  42582. BABYLON.serialize("roughness")
  42583. ], StandardMaterial.prototype, "_roughness", void 0);
  42584. __decorate([
  42585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42586. ], StandardMaterial.prototype, "roughness", void 0);
  42587. __decorate([
  42588. BABYLON.serialize()
  42589. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42590. __decorate([
  42591. BABYLON.serialize()
  42592. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42593. __decorate([
  42594. BABYLON.serialize()
  42595. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42596. __decorate([
  42597. BABYLON.serialize("useLightmapAsShadowmap")
  42598. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42599. __decorate([
  42600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42601. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42602. __decorate([
  42603. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42604. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42605. __decorate([
  42606. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42607. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42608. __decorate([
  42609. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42610. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42611. __decorate([
  42612. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42613. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42614. __decorate([
  42615. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42616. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42617. __decorate([
  42618. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42619. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42620. __decorate([
  42621. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42622. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42623. __decorate([
  42624. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42625. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42626. __decorate([
  42627. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42628. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42629. __decorate([
  42630. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42631. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42632. __decorate([
  42633. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42634. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42635. __decorate([
  42636. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42637. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42638. __decorate([
  42639. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42640. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42641. __decorate([
  42642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42643. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42644. __decorate([
  42645. BABYLON.serialize("maxSimultaneousLights")
  42646. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42647. __decorate([
  42648. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42649. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42650. __decorate([
  42651. BABYLON.serialize("invertNormalMapX")
  42652. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42653. __decorate([
  42654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42655. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42656. __decorate([
  42657. BABYLON.serialize("invertNormalMapY")
  42658. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42659. __decorate([
  42660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42661. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42662. __decorate([
  42663. BABYLON.serialize("twoSidedLighting")
  42664. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42665. __decorate([
  42666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42667. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42668. __decorate([
  42669. BABYLON.serialize()
  42670. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42671. return StandardMaterial;
  42672. }(BABYLON.PushMaterial));
  42673. BABYLON.StandardMaterial = StandardMaterial;
  42674. })(BABYLON || (BABYLON = {}));
  42675. //# sourceMappingURL=babylon.standardMaterial.js.map
  42676. var BABYLON;
  42677. (function (BABYLON) {
  42678. /**
  42679. * Class representing spherical polynomial coefficients to the 3rd degree
  42680. */
  42681. var SphericalPolynomial = /** @class */ (function () {
  42682. function SphericalPolynomial() {
  42683. /**
  42684. * The x coefficients of the spherical polynomial
  42685. */
  42686. this.x = BABYLON.Vector3.Zero();
  42687. /**
  42688. * The y coefficients of the spherical polynomial
  42689. */
  42690. this.y = BABYLON.Vector3.Zero();
  42691. /**
  42692. * The z coefficients of the spherical polynomial
  42693. */
  42694. this.z = BABYLON.Vector3.Zero();
  42695. /**
  42696. * The xx coefficients of the spherical polynomial
  42697. */
  42698. this.xx = BABYLON.Vector3.Zero();
  42699. /**
  42700. * The yy coefficients of the spherical polynomial
  42701. */
  42702. this.yy = BABYLON.Vector3.Zero();
  42703. /**
  42704. * The zz coefficients of the spherical polynomial
  42705. */
  42706. this.zz = BABYLON.Vector3.Zero();
  42707. /**
  42708. * The xy coefficients of the spherical polynomial
  42709. */
  42710. this.xy = BABYLON.Vector3.Zero();
  42711. /**
  42712. * The yz coefficients of the spherical polynomial
  42713. */
  42714. this.yz = BABYLON.Vector3.Zero();
  42715. /**
  42716. * The zx coefficients of the spherical polynomial
  42717. */
  42718. this.zx = BABYLON.Vector3.Zero();
  42719. }
  42720. /**
  42721. * Adds an ambient color to the spherical polynomial
  42722. * @param color the color to add
  42723. */
  42724. SphericalPolynomial.prototype.addAmbient = function (color) {
  42725. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42726. this.xx = this.xx.add(colorVector);
  42727. this.yy = this.yy.add(colorVector);
  42728. this.zz = this.zz.add(colorVector);
  42729. };
  42730. /**
  42731. * Scales the spherical polynomial by the given amount
  42732. * @param scale the amount to scale
  42733. */
  42734. SphericalPolynomial.prototype.scale = function (scale) {
  42735. this.x = this.x.scale(scale);
  42736. this.y = this.y.scale(scale);
  42737. this.z = this.z.scale(scale);
  42738. this.xx = this.xx.scale(scale);
  42739. this.yy = this.yy.scale(scale);
  42740. this.zz = this.zz.scale(scale);
  42741. this.yz = this.yz.scale(scale);
  42742. this.zx = this.zx.scale(scale);
  42743. this.xy = this.xy.scale(scale);
  42744. };
  42745. /**
  42746. * Gets the spherical polynomial from harmonics
  42747. * @param harmonics the spherical harmonics
  42748. * @returns the spherical polynomial
  42749. */
  42750. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42751. var result = new SphericalPolynomial();
  42752. result.x = harmonics.l11.scale(1.02333);
  42753. result.y = harmonics.l1_1.scale(1.02333);
  42754. result.z = harmonics.l10.scale(1.02333);
  42755. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42756. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42757. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42758. result.yz = harmonics.l2_1.scale(0.858086);
  42759. result.zx = harmonics.l21.scale(0.858086);
  42760. result.xy = harmonics.l2_2.scale(0.858086);
  42761. result.scale(1.0 / Math.PI);
  42762. return result;
  42763. };
  42764. /**
  42765. * Constructs a spherical polynomial from an array.
  42766. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42767. * @returns the spherical polynomial
  42768. */
  42769. SphericalPolynomial.FromArray = function (data) {
  42770. var sp = new SphericalPolynomial();
  42771. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42772. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42773. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42774. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42775. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42776. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42777. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42778. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42779. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42780. return sp;
  42781. };
  42782. return SphericalPolynomial;
  42783. }());
  42784. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42785. /**
  42786. * Class representing spherical harmonics coefficients to the 3rd degree
  42787. */
  42788. var SphericalHarmonics = /** @class */ (function () {
  42789. function SphericalHarmonics() {
  42790. /**
  42791. * The l0,0 coefficients of the spherical harmonics
  42792. */
  42793. this.l00 = BABYLON.Vector3.Zero();
  42794. /**
  42795. * The l1,-1 coefficients of the spherical harmonics
  42796. */
  42797. this.l1_1 = BABYLON.Vector3.Zero();
  42798. /**
  42799. * The l1,0 coefficients of the spherical harmonics
  42800. */
  42801. this.l10 = BABYLON.Vector3.Zero();
  42802. /**
  42803. * The l1,1 coefficients of the spherical harmonics
  42804. */
  42805. this.l11 = BABYLON.Vector3.Zero();
  42806. /**
  42807. * The l2,-2 coefficients of the spherical harmonics
  42808. */
  42809. this.l2_2 = BABYLON.Vector3.Zero();
  42810. /**
  42811. * The l2,-1 coefficients of the spherical harmonics
  42812. */
  42813. this.l2_1 = BABYLON.Vector3.Zero();
  42814. /**
  42815. * The l2,0 coefficients of the spherical harmonics
  42816. */
  42817. this.l20 = BABYLON.Vector3.Zero();
  42818. /**
  42819. * The l2,1 coefficients of the spherical harmonics
  42820. */
  42821. this.l21 = BABYLON.Vector3.Zero();
  42822. /**
  42823. * The l2,2 coefficients of the spherical harmonics
  42824. */
  42825. this.lL22 = BABYLON.Vector3.Zero();
  42826. }
  42827. /**
  42828. * Adds a light to the spherical harmonics
  42829. * @param direction the direction of the light
  42830. * @param color the color of the light
  42831. * @param deltaSolidAngle the delta solid angle of the light
  42832. */
  42833. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42834. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42835. var c = colorVector.scale(deltaSolidAngle);
  42836. this.l00 = this.l00.add(c.scale(0.282095));
  42837. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42838. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42839. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42840. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42841. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42842. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42843. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42844. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42845. };
  42846. /**
  42847. * Scales the spherical harmonics by the given amount
  42848. * @param scale the amount to scale
  42849. */
  42850. SphericalHarmonics.prototype.scale = function (scale) {
  42851. this.l00 = this.l00.scale(scale);
  42852. this.l1_1 = this.l1_1.scale(scale);
  42853. this.l10 = this.l10.scale(scale);
  42854. this.l11 = this.l11.scale(scale);
  42855. this.l2_2 = this.l2_2.scale(scale);
  42856. this.l2_1 = this.l2_1.scale(scale);
  42857. this.l20 = this.l20.scale(scale);
  42858. this.l21 = this.l21.scale(scale);
  42859. this.lL22 = this.lL22.scale(scale);
  42860. };
  42861. /**
  42862. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42863. *
  42864. * ```
  42865. * E_lm = A_l * L_lm
  42866. * ```
  42867. *
  42868. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42869. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42870. * the scaling factors are given in equation 9.
  42871. */
  42872. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42873. // Constant (Band 0)
  42874. this.l00 = this.l00.scale(3.141593);
  42875. // Linear (Band 1)
  42876. this.l1_1 = this.l1_1.scale(2.094395);
  42877. this.l10 = this.l10.scale(2.094395);
  42878. this.l11 = this.l11.scale(2.094395);
  42879. // Quadratic (Band 2)
  42880. this.l2_2 = this.l2_2.scale(0.785398);
  42881. this.l2_1 = this.l2_1.scale(0.785398);
  42882. this.l20 = this.l20.scale(0.785398);
  42883. this.l21 = this.l21.scale(0.785398);
  42884. this.lL22 = this.lL22.scale(0.785398);
  42885. };
  42886. /**
  42887. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42888. *
  42889. * ```
  42890. * L = (1/pi) * E * rho
  42891. * ```
  42892. *
  42893. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42894. */
  42895. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42896. this.scale(1.0 / Math.PI);
  42897. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42898. // (The pixel shader must apply albedo after texture fetches, etc).
  42899. };
  42900. /**
  42901. * Gets the spherical harmonics from polynomial
  42902. * @param polynomial the spherical polynomial
  42903. * @returns the spherical harmonics
  42904. */
  42905. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42906. var result = new SphericalHarmonics();
  42907. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42908. result.l1_1 = polynomial.y.scale(0.977204);
  42909. result.l10 = polynomial.z.scale(0.977204);
  42910. result.l11 = polynomial.x.scale(0.977204);
  42911. result.l2_2 = polynomial.xy.scale(1.16538);
  42912. result.l2_1 = polynomial.yz.scale(1.16538);
  42913. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  42914. result.l21 = polynomial.zx.scale(1.16538);
  42915. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  42916. result.scale(Math.PI);
  42917. return result;
  42918. };
  42919. /**
  42920. * Constructs a spherical harmonics from an array.
  42921. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  42922. * @returns the spherical harmonics
  42923. */
  42924. SphericalHarmonics.FromArray = function (data) {
  42925. var sh = new SphericalHarmonics();
  42926. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  42927. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  42928. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  42929. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  42930. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  42931. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  42932. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  42933. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  42934. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  42935. return sh;
  42936. };
  42937. return SphericalHarmonics;
  42938. }());
  42939. BABYLON.SphericalHarmonics = SphericalHarmonics;
  42940. })(BABYLON || (BABYLON = {}));
  42941. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  42942. var BABYLON;
  42943. (function (BABYLON) {
  42944. var FileFaceOrientation = /** @class */ (function () {
  42945. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42946. this.name = name;
  42947. this.worldAxisForNormal = worldAxisForNormal;
  42948. this.worldAxisForFileX = worldAxisForFileX;
  42949. this.worldAxisForFileY = worldAxisForFileY;
  42950. }
  42951. return FileFaceOrientation;
  42952. }());
  42953. ;
  42954. /**
  42955. * Helper class dealing with the extraction of spherical polynomial dataArray
  42956. * from a cube map.
  42957. */
  42958. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  42959. function CubeMapToSphericalPolynomialTools() {
  42960. }
  42961. /**
  42962. * Converts a texture to the according Spherical Polynomial data.
  42963. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42964. *
  42965. * @param texture The texture to extract the information from.
  42966. * @return The Spherical Polynomial data.
  42967. */
  42968. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  42969. if (!texture.isCube) {
  42970. // Only supports cube Textures currently.
  42971. return null;
  42972. }
  42973. var size = texture.getSize().width;
  42974. var right = texture.readPixels(0);
  42975. var left = texture.readPixels(1);
  42976. var up;
  42977. var down;
  42978. if (texture.isRenderTarget) {
  42979. up = texture.readPixels(3);
  42980. down = texture.readPixels(2);
  42981. }
  42982. else {
  42983. up = texture.readPixels(2);
  42984. down = texture.readPixels(3);
  42985. }
  42986. var front = texture.readPixels(4);
  42987. var back = texture.readPixels(5);
  42988. var gammaSpace = texture.gammaSpace;
  42989. // Always read as RGBA.
  42990. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  42991. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42992. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  42993. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42994. }
  42995. var cubeInfo = {
  42996. size: size,
  42997. right: right,
  42998. left: left,
  42999. up: up,
  43000. down: down,
  43001. front: front,
  43002. back: back,
  43003. format: format,
  43004. type: type,
  43005. gammaSpace: gammaSpace,
  43006. };
  43007. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43008. };
  43009. /**
  43010. * Converts a cubemap to the according Spherical Polynomial data.
  43011. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43012. *
  43013. * @param cubeInfo The Cube map to extract the information from.
  43014. * @return The Spherical Polynomial data.
  43015. */
  43016. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43017. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43018. var totalSolidAngle = 0.0;
  43019. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43020. var du = 2.0 / cubeInfo.size;
  43021. var dv = du;
  43022. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43023. var minUV = du * 0.5 - 1.0;
  43024. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43025. var fileFace = this.FileFaces[faceIndex];
  43026. var dataArray = cubeInfo[fileFace.name];
  43027. var v = minUV;
  43028. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43029. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43030. // Because SP is still linear, so summation is fine in that basis.
  43031. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43032. for (var y = 0; y < cubeInfo.size; y++) {
  43033. var u = minUV;
  43034. for (var x = 0; x < cubeInfo.size; x++) {
  43035. // World direction (not normalised)
  43036. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43037. worldDirection.normalize();
  43038. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43039. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43040. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43041. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43042. // Handle Integer types.
  43043. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43044. r /= 255;
  43045. g /= 255;
  43046. b /= 255;
  43047. }
  43048. // Handle Gamma space textures.
  43049. if (cubeInfo.gammaSpace) {
  43050. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43051. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43052. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43053. }
  43054. var color = new BABYLON.Color3(r, g, b);
  43055. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43056. totalSolidAngle += deltaSolidAngle;
  43057. u += du;
  43058. }
  43059. v += dv;
  43060. }
  43061. }
  43062. // Solid angle for entire sphere is 4*pi
  43063. var sphereSolidAngle = 4.0 * Math.PI;
  43064. // Adjust the solid angle to allow for how many faces we processed.
  43065. var facesProcessed = 6.0;
  43066. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43067. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43068. // This is needed because the numerical integration over the cube uses a
  43069. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43070. // and also to compensate for accumulative error due to float precision in the summation.
  43071. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43072. sphericalHarmonics.scale(correctionFactor);
  43073. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43074. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43075. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43076. };
  43077. CubeMapToSphericalPolynomialTools.FileFaces = [
  43078. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43079. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43080. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43081. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43082. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43083. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43084. ];
  43085. return CubeMapToSphericalPolynomialTools;
  43086. }());
  43087. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43088. })(BABYLON || (BABYLON = {}));
  43089. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43090. var BABYLON;
  43091. (function (BABYLON) {
  43092. /**
  43093. * Manages the defines for the PBR Material.
  43094. * @hiddenChildren
  43095. */
  43096. var PBRMaterialDefines = /** @class */ (function (_super) {
  43097. __extends(PBRMaterialDefines, _super);
  43098. /**
  43099. * Initializes the PBR Material defines.
  43100. */
  43101. function PBRMaterialDefines() {
  43102. var _this = _super.call(this) || this;
  43103. _this.PBR = true;
  43104. _this.MAINUV1 = false;
  43105. _this.MAINUV2 = false;
  43106. _this.UV1 = false;
  43107. _this.UV2 = false;
  43108. _this.ALBEDO = false;
  43109. _this.ALBEDODIRECTUV = 0;
  43110. _this.VERTEXCOLOR = false;
  43111. _this.AMBIENT = false;
  43112. _this.AMBIENTDIRECTUV = 0;
  43113. _this.AMBIENTINGRAYSCALE = false;
  43114. _this.OPACITY = false;
  43115. _this.VERTEXALPHA = false;
  43116. _this.OPACITYDIRECTUV = 0;
  43117. _this.OPACITYRGB = false;
  43118. _this.ALPHATEST = false;
  43119. _this.DEPTHPREPASS = false;
  43120. _this.ALPHABLEND = false;
  43121. _this.ALPHAFROMALBEDO = false;
  43122. _this.ALPHATESTVALUE = "0.5";
  43123. _this.SPECULAROVERALPHA = false;
  43124. _this.RADIANCEOVERALPHA = false;
  43125. _this.ALPHAFRESNEL = false;
  43126. _this.LINEARALPHAFRESNEL = false;
  43127. _this.PREMULTIPLYALPHA = false;
  43128. _this.EMISSIVE = false;
  43129. _this.EMISSIVEDIRECTUV = 0;
  43130. _this.REFLECTIVITY = false;
  43131. _this.REFLECTIVITYDIRECTUV = 0;
  43132. _this.SPECULARTERM = false;
  43133. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43134. _this.MICROSURFACEAUTOMATIC = false;
  43135. _this.LODBASEDMICROSFURACE = false;
  43136. _this.MICROSURFACEMAP = false;
  43137. _this.MICROSURFACEMAPDIRECTUV = 0;
  43138. _this.METALLICWORKFLOW = false;
  43139. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43140. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43141. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43142. _this.AOSTOREINMETALMAPRED = false;
  43143. _this.ENVIRONMENTBRDF = false;
  43144. _this.NORMAL = false;
  43145. _this.TANGENT = false;
  43146. _this.BUMP = false;
  43147. _this.BUMPDIRECTUV = 0;
  43148. _this.OBJECTSPACE_NORMALMAP = false;
  43149. _this.PARALLAX = false;
  43150. _this.PARALLAXOCCLUSION = false;
  43151. _this.NORMALXYSCALE = true;
  43152. _this.LIGHTMAP = false;
  43153. _this.LIGHTMAPDIRECTUV = 0;
  43154. _this.USELIGHTMAPASSHADOWMAP = false;
  43155. _this.GAMMALIGHTMAP = false;
  43156. _this.REFLECTION = false;
  43157. _this.REFLECTIONMAP_3D = false;
  43158. _this.REFLECTIONMAP_SPHERICAL = false;
  43159. _this.REFLECTIONMAP_PLANAR = false;
  43160. _this.REFLECTIONMAP_CUBIC = false;
  43161. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43162. _this.REFLECTIONMAP_PROJECTION = false;
  43163. _this.REFLECTIONMAP_SKYBOX = false;
  43164. _this.REFLECTIONMAP_EXPLICIT = false;
  43165. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43166. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43167. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43168. _this.INVERTCUBICMAP = false;
  43169. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43170. _this.USESPHERICALINVERTEX = false;
  43171. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43172. _this.LODINREFLECTIONALPHA = false;
  43173. _this.GAMMAREFLECTION = false;
  43174. _this.RGBDREFLECTION = false;
  43175. _this.RADIANCEOCCLUSION = false;
  43176. _this.HORIZONOCCLUSION = false;
  43177. _this.REFRACTION = false;
  43178. _this.REFRACTIONMAP_3D = false;
  43179. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43180. _this.LODINREFRACTIONALPHA = false;
  43181. _this.GAMMAREFRACTION = false;
  43182. _this.RGBDREFRACTION = false;
  43183. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43184. _this.INSTANCES = false;
  43185. _this.NUM_BONE_INFLUENCERS = 0;
  43186. _this.BonesPerMesh = 0;
  43187. _this.NONUNIFORMSCALING = false;
  43188. _this.MORPHTARGETS = false;
  43189. _this.MORPHTARGETS_NORMAL = false;
  43190. _this.MORPHTARGETS_TANGENT = false;
  43191. _this.NUM_MORPH_INFLUENCERS = 0;
  43192. _this.IMAGEPROCESSING = false;
  43193. _this.VIGNETTE = false;
  43194. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43195. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43196. _this.TONEMAPPING = false;
  43197. _this.CONTRAST = false;
  43198. _this.COLORCURVES = false;
  43199. _this.COLORGRADING = false;
  43200. _this.COLORGRADING3D = false;
  43201. _this.SAMPLER3DGREENDEPTH = false;
  43202. _this.SAMPLER3DBGRMAP = false;
  43203. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43204. _this.EXPOSURE = false;
  43205. _this.USEPHYSICALLIGHTFALLOFF = false;
  43206. _this.TWOSIDEDLIGHTING = false;
  43207. _this.SHADOWFLOAT = false;
  43208. _this.CLIPPLANE = false;
  43209. _this.POINTSIZE = false;
  43210. _this.FOG = false;
  43211. _this.LOGARITHMICDEPTH = false;
  43212. _this.FORCENORMALFORWARD = false;
  43213. _this.SPECULARAA = false;
  43214. _this.UNLIT = false;
  43215. _this.rebuild();
  43216. return _this;
  43217. }
  43218. /**
  43219. * Resets the PBR Material defines.
  43220. */
  43221. PBRMaterialDefines.prototype.reset = function () {
  43222. _super.prototype.reset.call(this);
  43223. this.ALPHATESTVALUE = "0.5";
  43224. this.PBR = true;
  43225. };
  43226. return PBRMaterialDefines;
  43227. }(BABYLON.MaterialDefines));
  43228. /**
  43229. * The Physically based material base class of BJS.
  43230. *
  43231. * This offers the main features of a standard PBR material.
  43232. * For more information, please refer to the documentation :
  43233. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43234. */
  43235. var PBRBaseMaterial = /** @class */ (function (_super) {
  43236. __extends(PBRBaseMaterial, _super);
  43237. /**
  43238. * Instantiates a new PBRMaterial instance.
  43239. *
  43240. * @param name The material name
  43241. * @param scene The scene the material will be use in.
  43242. */
  43243. function PBRBaseMaterial(name, scene) {
  43244. var _this = _super.call(this, name, scene) || this;
  43245. /**
  43246. * Intensity of the direct lights e.g. the four lights available in your scene.
  43247. * This impacts both the direct diffuse and specular highlights.
  43248. */
  43249. _this._directIntensity = 1.0;
  43250. /**
  43251. * Intensity of the emissive part of the material.
  43252. * This helps controlling the emissive effect without modifying the emissive color.
  43253. */
  43254. _this._emissiveIntensity = 1.0;
  43255. /**
  43256. * Intensity of the environment e.g. how much the environment will light the object
  43257. * either through harmonics for rough material or through the refelction for shiny ones.
  43258. */
  43259. _this._environmentIntensity = 1.0;
  43260. /**
  43261. * This is a special control allowing the reduction of the specular highlights coming from the
  43262. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43263. */
  43264. _this._specularIntensity = 1.0;
  43265. /**
  43266. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43267. */
  43268. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43269. /**
  43270. * Debug Control allowing disabling the bump map on this material.
  43271. */
  43272. _this._disableBumpMap = false;
  43273. /**
  43274. * AKA Occlusion Texture Intensity in other nomenclature.
  43275. */
  43276. _this._ambientTextureStrength = 1.0;
  43277. /**
  43278. * The color of a material in ambient lighting.
  43279. */
  43280. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43281. /**
  43282. * AKA Diffuse Color in other nomenclature.
  43283. */
  43284. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43285. /**
  43286. * AKA Specular Color in other nomenclature.
  43287. */
  43288. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43289. /**
  43290. * The color applied when light is reflected from a material.
  43291. */
  43292. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43293. /**
  43294. * The color applied when light is emitted from a material.
  43295. */
  43296. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43297. /**
  43298. * AKA Glossiness in other nomenclature.
  43299. */
  43300. _this._microSurface = 0.9;
  43301. /**
  43302. * source material index of refraction (IOR)' / 'destination material IOR.
  43303. */
  43304. _this._indexOfRefraction = 0.66;
  43305. /**
  43306. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43307. */
  43308. _this._invertRefractionY = false;
  43309. /**
  43310. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43311. * Materials half opaque for instance using refraction could benefit from this control.
  43312. */
  43313. _this._linkRefractionWithTransparency = false;
  43314. /**
  43315. * Specifies that the material will use the light map as a show map.
  43316. */
  43317. _this._useLightmapAsShadowmap = false;
  43318. /**
  43319. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43320. * makes the reflect vector face the model (under horizon).
  43321. */
  43322. _this._useHorizonOcclusion = true;
  43323. /**
  43324. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43325. * too much the area relying on ambient texture to define their ambient occlusion.
  43326. */
  43327. _this._useRadianceOcclusion = true;
  43328. /**
  43329. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43330. */
  43331. _this._useAlphaFromAlbedoTexture = false;
  43332. /**
  43333. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43334. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43335. */
  43336. _this._useSpecularOverAlpha = true;
  43337. /**
  43338. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43339. */
  43340. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43341. /**
  43342. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43343. */
  43344. _this._useRoughnessFromMetallicTextureAlpha = true;
  43345. /**
  43346. * Specifies if the metallic texture contains the roughness information in its green channel.
  43347. */
  43348. _this._useRoughnessFromMetallicTextureGreen = false;
  43349. /**
  43350. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43351. */
  43352. _this._useMetallnessFromMetallicTextureBlue = false;
  43353. /**
  43354. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43355. */
  43356. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43357. /**
  43358. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43359. */
  43360. _this._useAmbientInGrayScale = false;
  43361. /**
  43362. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43363. * The material will try to infer what glossiness each pixel should be.
  43364. */
  43365. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43366. /**
  43367. * BJS is using an harcoded light falloff based on a manually sets up range.
  43368. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43369. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43370. */
  43371. _this._usePhysicalLightFalloff = true;
  43372. /**
  43373. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43374. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43375. */
  43376. _this._useRadianceOverAlpha = true;
  43377. /**
  43378. * Allows using an object space normal map (instead of tangent space).
  43379. */
  43380. _this._useObjectSpaceNormalMap = false;
  43381. /**
  43382. * Allows using the bump map in parallax mode.
  43383. */
  43384. _this._useParallax = false;
  43385. /**
  43386. * Allows using the bump map in parallax occlusion mode.
  43387. */
  43388. _this._useParallaxOcclusion = false;
  43389. /**
  43390. * Controls the scale bias of the parallax mode.
  43391. */
  43392. _this._parallaxScaleBias = 0.05;
  43393. /**
  43394. * If sets to true, disables all the lights affecting the material.
  43395. */
  43396. _this._disableLighting = false;
  43397. /**
  43398. * Number of Simultaneous lights allowed on the material.
  43399. */
  43400. _this._maxSimultaneousLights = 4;
  43401. /**
  43402. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43403. */
  43404. _this._invertNormalMapX = false;
  43405. /**
  43406. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43407. */
  43408. _this._invertNormalMapY = false;
  43409. /**
  43410. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43411. */
  43412. _this._twoSidedLighting = false;
  43413. /**
  43414. * Defines the alpha limits in alpha test mode.
  43415. */
  43416. _this._alphaCutOff = 0.4;
  43417. /**
  43418. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43419. */
  43420. _this._forceAlphaTest = false;
  43421. /**
  43422. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43423. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43424. */
  43425. _this._useAlphaFresnel = false;
  43426. /**
  43427. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43428. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43429. */
  43430. _this._useLinearAlphaFresnel = false;
  43431. /**
  43432. * The transparency mode of the material.
  43433. */
  43434. _this._transparencyMode = null;
  43435. /**
  43436. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43437. * from cos thetav and roughness:
  43438. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43439. */
  43440. _this._environmentBRDFTexture = null;
  43441. /**
  43442. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43443. */
  43444. _this._forceIrradianceInFragment = false;
  43445. /**
  43446. * Force normal to face away from face.
  43447. */
  43448. _this._forceNormalForward = false;
  43449. /**
  43450. * Enables specular anti aliasing in the PBR shader.
  43451. * It will both interacts on the Geometry for analytical and IBL lighting.
  43452. * It also prefilter the roughness map based on the bump values.
  43453. */
  43454. _this._enableSpecularAntiAliasing = false;
  43455. /**
  43456. * Stores the available render targets.
  43457. */
  43458. _this._renderTargets = new BABYLON.SmartArray(16);
  43459. /**
  43460. * Sets the global ambient color for the material used in lighting calculations.
  43461. */
  43462. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43463. /**
  43464. * If set to true, no lighting calculations will be applied.
  43465. */
  43466. _this._unlit = false;
  43467. // Setup the default processing configuration to the scene.
  43468. _this._attachImageProcessingConfiguration(null);
  43469. _this.getRenderTargetTextures = function () {
  43470. _this._renderTargets.reset();
  43471. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43472. _this._renderTargets.push(_this._reflectionTexture);
  43473. }
  43474. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43475. _this._renderTargets.push(_this._refractionTexture);
  43476. }
  43477. return _this._renderTargets;
  43478. };
  43479. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43480. return _this;
  43481. }
  43482. /**
  43483. * Attaches a new image processing configuration to the PBR Material.
  43484. * @param configuration
  43485. */
  43486. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43487. var _this = this;
  43488. if (configuration === this._imageProcessingConfiguration) {
  43489. return;
  43490. }
  43491. // Detaches observer.
  43492. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43493. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43494. }
  43495. // Pick the scene configuration if needed.
  43496. if (!configuration) {
  43497. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43498. }
  43499. else {
  43500. this._imageProcessingConfiguration = configuration;
  43501. }
  43502. // Attaches observer.
  43503. if (this._imageProcessingConfiguration) {
  43504. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43505. _this._markAllSubMeshesAsImageProcessingDirty();
  43506. });
  43507. }
  43508. };
  43509. /**
  43510. * Gets the name of the material class.
  43511. */
  43512. PBRBaseMaterial.prototype.getClassName = function () {
  43513. return "PBRBaseMaterial";
  43514. };
  43515. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43516. /**
  43517. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43518. */
  43519. get: function () {
  43520. return this._useLogarithmicDepth;
  43521. },
  43522. /**
  43523. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43524. */
  43525. set: function (value) {
  43526. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43527. },
  43528. enumerable: true,
  43529. configurable: true
  43530. });
  43531. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43532. /**
  43533. * Gets the current transparency mode.
  43534. */
  43535. get: function () {
  43536. return this._transparencyMode;
  43537. },
  43538. /**
  43539. * Sets the transparency mode of the material.
  43540. *
  43541. * | Value | Type | Description |
  43542. * | ----- | ----------------------------------- | ----------- |
  43543. * | 0 | OPAQUE | |
  43544. * | 1 | ALPHATEST | |
  43545. * | 2 | ALPHABLEND | |
  43546. * | 3 | ALPHATESTANDBLEND | |
  43547. *
  43548. */
  43549. set: function (value) {
  43550. if (this._transparencyMode === value) {
  43551. return;
  43552. }
  43553. this._transparencyMode = value;
  43554. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43555. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43556. },
  43557. enumerable: true,
  43558. configurable: true
  43559. });
  43560. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43561. /**
  43562. * Returns true if alpha blending should be disabled.
  43563. */
  43564. get: function () {
  43565. return (this._linkRefractionWithTransparency ||
  43566. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43567. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43568. },
  43569. enumerable: true,
  43570. configurable: true
  43571. });
  43572. /**
  43573. * Specifies whether or not this material should be rendered in alpha blend mode.
  43574. */
  43575. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43576. if (this._disableAlphaBlending) {
  43577. return false;
  43578. }
  43579. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43580. };
  43581. /**
  43582. * Specifies if the mesh will require alpha blending.
  43583. * @param mesh - BJS mesh.
  43584. */
  43585. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43586. if (this._disableAlphaBlending) {
  43587. return false;
  43588. }
  43589. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43590. };
  43591. /**
  43592. * Specifies whether or not this material should be rendered in alpha test mode.
  43593. */
  43594. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43595. if (this._forceAlphaTest) {
  43596. return true;
  43597. }
  43598. if (this._linkRefractionWithTransparency) {
  43599. return false;
  43600. }
  43601. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43602. };
  43603. /**
  43604. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43605. */
  43606. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43607. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43608. };
  43609. /**
  43610. * Gets the texture used for the alpha test.
  43611. */
  43612. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43613. return this._albedoTexture;
  43614. };
  43615. /**
  43616. * Specifies that the submesh is ready to be used.
  43617. * @param mesh - BJS mesh.
  43618. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43619. * @param useInstances - Specifies that instances should be used.
  43620. * @returns - boolean indicating that the submesh is ready or not.
  43621. */
  43622. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43623. if (subMesh.effect && this.isFrozen) {
  43624. if (this._wasPreviouslyReady) {
  43625. return true;
  43626. }
  43627. }
  43628. if (!subMesh._materialDefines) {
  43629. subMesh._materialDefines = new PBRMaterialDefines();
  43630. }
  43631. var defines = subMesh._materialDefines;
  43632. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43633. if (defines._renderId === this.getScene().getRenderId()) {
  43634. return true;
  43635. }
  43636. }
  43637. var scene = this.getScene();
  43638. var engine = scene.getEngine();
  43639. if (defines._areTexturesDirty) {
  43640. if (scene.texturesEnabled) {
  43641. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43642. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43643. return false;
  43644. }
  43645. }
  43646. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43647. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43648. return false;
  43649. }
  43650. }
  43651. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43652. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43653. return false;
  43654. }
  43655. }
  43656. var reflectionTexture = this._getReflectionTexture();
  43657. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43658. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43659. return false;
  43660. }
  43661. }
  43662. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43663. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43664. return false;
  43665. }
  43666. }
  43667. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43668. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43669. return false;
  43670. }
  43671. }
  43672. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43673. if (this._metallicTexture) {
  43674. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43675. return false;
  43676. }
  43677. }
  43678. else if (this._reflectivityTexture) {
  43679. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43680. return false;
  43681. }
  43682. }
  43683. if (this._microSurfaceTexture) {
  43684. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43685. return false;
  43686. }
  43687. }
  43688. }
  43689. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43690. // Bump texture cannot be not blocking.
  43691. if (!this._bumpTexture.isReady()) {
  43692. return false;
  43693. }
  43694. }
  43695. var refractionTexture = this._getRefractionTexture();
  43696. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43697. if (!refractionTexture.isReadyOrNotBlocking()) {
  43698. return false;
  43699. }
  43700. }
  43701. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43702. // This is blocking.
  43703. if (!this._environmentBRDFTexture.isReady()) {
  43704. return false;
  43705. }
  43706. }
  43707. }
  43708. }
  43709. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43710. if (!this._imageProcessingConfiguration.isReady()) {
  43711. return false;
  43712. }
  43713. }
  43714. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43715. mesh.createNormals(true);
  43716. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43717. }
  43718. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43719. if (effect) {
  43720. scene.resetCachedMaterial();
  43721. subMesh.setEffect(effect, defines);
  43722. this.buildUniformLayout();
  43723. }
  43724. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43725. return false;
  43726. }
  43727. defines._renderId = scene.getRenderId();
  43728. this._wasPreviouslyReady = true;
  43729. return true;
  43730. };
  43731. /**
  43732. * Specifies if the material uses metallic roughness workflow.
  43733. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43734. */
  43735. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43736. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43737. return true;
  43738. }
  43739. return false;
  43740. };
  43741. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43742. if (onCompiled === void 0) { onCompiled = null; }
  43743. if (onError === void 0) { onError = null; }
  43744. if (useInstances === void 0) { useInstances = null; }
  43745. if (useClipPlane === void 0) { useClipPlane = null; }
  43746. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43747. if (!defines.isDirty) {
  43748. return null;
  43749. }
  43750. defines.markAsProcessed();
  43751. var scene = this.getScene();
  43752. var engine = scene.getEngine();
  43753. // Fallbacks
  43754. var fallbacks = new BABYLON.EffectFallbacks();
  43755. var fallbackRank = 0;
  43756. if (defines.USESPHERICALINVERTEX) {
  43757. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43758. }
  43759. if (defines.FOG) {
  43760. fallbacks.addFallback(fallbackRank, "FOG");
  43761. }
  43762. if (defines.SPECULARAA) {
  43763. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43764. }
  43765. if (defines.POINTSIZE) {
  43766. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43767. }
  43768. if (defines.LOGARITHMICDEPTH) {
  43769. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43770. }
  43771. if (defines.PARALLAX) {
  43772. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43773. }
  43774. if (defines.PARALLAXOCCLUSION) {
  43775. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43776. }
  43777. if (defines.ENVIRONMENTBRDF) {
  43778. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43779. }
  43780. if (defines.TANGENT) {
  43781. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43782. }
  43783. if (defines.BUMP) {
  43784. fallbacks.addFallback(fallbackRank++, "BUMP");
  43785. }
  43786. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43787. if (defines.SPECULARTERM) {
  43788. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43789. }
  43790. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43791. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43792. }
  43793. if (defines.LIGHTMAP) {
  43794. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43795. }
  43796. if (defines.NORMAL) {
  43797. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43798. }
  43799. if (defines.AMBIENT) {
  43800. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43801. }
  43802. if (defines.EMISSIVE) {
  43803. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43804. }
  43805. if (defines.VERTEXCOLOR) {
  43806. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43807. }
  43808. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43809. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43810. }
  43811. if (defines.MORPHTARGETS) {
  43812. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43813. }
  43814. //Attributes
  43815. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43816. if (defines.NORMAL) {
  43817. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43818. }
  43819. if (defines.TANGENT) {
  43820. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43821. }
  43822. if (defines.UV1) {
  43823. attribs.push(BABYLON.VertexBuffer.UVKind);
  43824. }
  43825. if (defines.UV2) {
  43826. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43827. }
  43828. if (defines.VERTEXCOLOR) {
  43829. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43830. }
  43831. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43832. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43833. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43834. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43835. "vFogInfos", "vFogColor", "pointSize",
  43836. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43837. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43838. "mBones",
  43839. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43840. "vLightingIntensity",
  43841. "logarithmicDepthConstant",
  43842. "vSphericalX", "vSphericalY", "vSphericalZ",
  43843. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43844. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43845. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43846. "vTangentSpaceParams"
  43847. ];
  43848. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43849. "bumpSampler", "lightmapSampler", "opacitySampler",
  43850. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43851. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43852. "microSurfaceSampler", "environmentBrdfSampler"];
  43853. var uniformBuffers = ["Material", "Scene"];
  43854. if (BABYLON.ImageProcessingConfiguration) {
  43855. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43856. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43857. }
  43858. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43859. uniformsNames: uniforms,
  43860. uniformBuffersNames: uniformBuffers,
  43861. samplers: samplers,
  43862. defines: defines,
  43863. maxSimultaneousLights: this._maxSimultaneousLights
  43864. });
  43865. var join = defines.toString();
  43866. return engine.createEffect("pbr", {
  43867. attributes: attribs,
  43868. uniformsNames: uniforms,
  43869. uniformBuffersNames: uniformBuffers,
  43870. samplers: samplers,
  43871. defines: join,
  43872. fallbacks: fallbacks,
  43873. onCompiled: onCompiled,
  43874. onError: onError,
  43875. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43876. }, engine);
  43877. };
  43878. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43879. if (useInstances === void 0) { useInstances = null; }
  43880. if (useClipPlane === void 0) { useClipPlane = null; }
  43881. var scene = this.getScene();
  43882. var engine = scene.getEngine();
  43883. // Lights
  43884. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43885. defines._needNormals = true;
  43886. // Textures
  43887. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43888. if (defines._areTexturesDirty) {
  43889. defines._needUVs = false;
  43890. if (scene.texturesEnabled) {
  43891. if (scene.getEngine().getCaps().textureLOD) {
  43892. defines.LODBASEDMICROSFURACE = true;
  43893. }
  43894. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43895. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43896. }
  43897. else {
  43898. defines.ALBEDO = false;
  43899. }
  43900. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43901. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43902. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43903. }
  43904. else {
  43905. defines.AMBIENT = false;
  43906. }
  43907. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43908. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43909. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43910. }
  43911. else {
  43912. defines.OPACITY = false;
  43913. }
  43914. var reflectionTexture = this._getReflectionTexture();
  43915. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43916. defines.REFLECTION = true;
  43917. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43918. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43919. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43920. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43921. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43922. defines.INVERTCUBICMAP = true;
  43923. }
  43924. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43925. switch (reflectionTexture.coordinatesMode) {
  43926. case BABYLON.Texture.EXPLICIT_MODE:
  43927. defines.REFLECTIONMAP_EXPLICIT = true;
  43928. break;
  43929. case BABYLON.Texture.PLANAR_MODE:
  43930. defines.REFLECTIONMAP_PLANAR = true;
  43931. break;
  43932. case BABYLON.Texture.PROJECTION_MODE:
  43933. defines.REFLECTIONMAP_PROJECTION = true;
  43934. break;
  43935. case BABYLON.Texture.SKYBOX_MODE:
  43936. defines.REFLECTIONMAP_SKYBOX = true;
  43937. break;
  43938. case BABYLON.Texture.SPHERICAL_MODE:
  43939. defines.REFLECTIONMAP_SPHERICAL = true;
  43940. break;
  43941. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43942. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43943. break;
  43944. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43945. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43946. break;
  43947. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43948. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43949. break;
  43950. case BABYLON.Texture.CUBIC_MODE:
  43951. case BABYLON.Texture.INVCUBIC_MODE:
  43952. default:
  43953. defines.REFLECTIONMAP_CUBIC = true;
  43954. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43955. break;
  43956. }
  43957. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43958. if (reflectionTexture.sphericalPolynomial) {
  43959. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43960. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43961. defines.USESPHERICALINVERTEX = false;
  43962. }
  43963. else {
  43964. defines.USESPHERICALINVERTEX = true;
  43965. }
  43966. }
  43967. }
  43968. }
  43969. else {
  43970. defines.REFLECTION = false;
  43971. defines.REFLECTIONMAP_3D = false;
  43972. defines.REFLECTIONMAP_SPHERICAL = false;
  43973. defines.REFLECTIONMAP_PLANAR = false;
  43974. defines.REFLECTIONMAP_CUBIC = false;
  43975. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43976. defines.REFLECTIONMAP_PROJECTION = false;
  43977. defines.REFLECTIONMAP_SKYBOX = false;
  43978. defines.REFLECTIONMAP_EXPLICIT = false;
  43979. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43980. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43981. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43982. defines.INVERTCUBICMAP = false;
  43983. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43984. defines.USESPHERICALINVERTEX = false;
  43985. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43986. defines.LODINREFLECTIONALPHA = false;
  43987. defines.GAMMAREFLECTION = false;
  43988. defines.RGBDREFLECTION = false;
  43989. }
  43990. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43991. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43992. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43993. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43994. }
  43995. else {
  43996. defines.LIGHTMAP = false;
  43997. }
  43998. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43999. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44000. }
  44001. else {
  44002. defines.EMISSIVE = false;
  44003. }
  44004. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44005. if (this._metallicTexture) {
  44006. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44007. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44008. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44009. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44010. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44011. }
  44012. else if (this._reflectivityTexture) {
  44013. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44014. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44015. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44016. }
  44017. else {
  44018. defines.REFLECTIVITY = false;
  44019. }
  44020. if (this._microSurfaceTexture) {
  44021. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44022. }
  44023. else {
  44024. defines.MICROSURFACEMAP = false;
  44025. }
  44026. }
  44027. else {
  44028. defines.REFLECTIVITY = false;
  44029. defines.MICROSURFACEMAP = false;
  44030. }
  44031. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44032. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44033. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44034. defines.PARALLAX = true;
  44035. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44036. }
  44037. else {
  44038. defines.PARALLAX = false;
  44039. }
  44040. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44041. }
  44042. else {
  44043. defines.BUMP = false;
  44044. }
  44045. var refractionTexture = this._getRefractionTexture();
  44046. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44047. defines.REFRACTION = true;
  44048. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44049. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44050. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44051. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44052. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44053. if (this._linkRefractionWithTransparency) {
  44054. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44055. }
  44056. }
  44057. else {
  44058. defines.REFRACTION = false;
  44059. }
  44060. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44061. defines.ENVIRONMENTBRDF = true;
  44062. }
  44063. else {
  44064. defines.ENVIRONMENTBRDF = false;
  44065. }
  44066. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44067. defines.ALPHAFROMALBEDO = true;
  44068. }
  44069. else {
  44070. defines.ALPHAFROMALBEDO = false;
  44071. }
  44072. }
  44073. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44074. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44075. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44076. if (!this.backFaceCulling && this._twoSidedLighting) {
  44077. defines.TWOSIDEDLIGHTING = true;
  44078. }
  44079. else {
  44080. defines.TWOSIDEDLIGHTING = false;
  44081. }
  44082. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44083. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44084. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44085. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44086. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44087. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44088. }
  44089. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44090. this._imageProcessingConfiguration.prepareDefines(defines);
  44091. }
  44092. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44093. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44094. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44095. // Misc.
  44096. if (defines._areMiscDirty) {
  44097. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44098. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44099. }
  44100. // Values that need to be evaluated on every frame
  44101. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44102. // Attribs
  44103. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44104. };
  44105. /**
  44106. * Force shader compilation
  44107. */
  44108. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44109. var _this = this;
  44110. var localOptions = __assign({ clipPlane: false }, options);
  44111. var defines = new PBRMaterialDefines();
  44112. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44113. if (effect.isReady()) {
  44114. if (onCompiled) {
  44115. onCompiled(this);
  44116. }
  44117. }
  44118. else {
  44119. effect.onCompileObservable.add(function () {
  44120. if (onCompiled) {
  44121. onCompiled(_this);
  44122. }
  44123. });
  44124. }
  44125. };
  44126. /**
  44127. * Initializes the uniform buffer layout for the shader.
  44128. */
  44129. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44130. // Order is important !
  44131. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44132. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44133. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44134. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44135. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44136. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44137. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44138. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44139. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44140. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44141. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44142. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44143. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44144. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44145. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44146. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44147. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44148. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44149. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44150. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44151. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44152. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44153. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44154. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44155. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44156. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44157. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44158. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44159. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44160. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44161. this._uniformBuffer.addUniform("pointSize", 1);
  44162. this._uniformBuffer.create();
  44163. };
  44164. /**
  44165. * Unbinds the textures.
  44166. */
  44167. PBRBaseMaterial.prototype.unbind = function () {
  44168. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44169. this._uniformBuffer.setTexture("reflectionSampler", null);
  44170. }
  44171. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44172. this._uniformBuffer.setTexture("refractionSampler", null);
  44173. }
  44174. _super.prototype.unbind.call(this);
  44175. };
  44176. /**
  44177. * Binds the submesh data.
  44178. * @param world - The world matrix.
  44179. * @param mesh - The BJS mesh.
  44180. * @param subMesh - A submesh of the BJS mesh.
  44181. */
  44182. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44183. var scene = this.getScene();
  44184. var defines = subMesh._materialDefines;
  44185. if (!defines) {
  44186. return;
  44187. }
  44188. var effect = subMesh.effect;
  44189. if (!effect) {
  44190. return;
  44191. }
  44192. this._activeEffect = effect;
  44193. // Matrices
  44194. this.bindOnlyWorldMatrix(world);
  44195. // Normal Matrix
  44196. if (defines.OBJECTSPACE_NORMALMAP) {
  44197. world.toNormalMatrix(this._normalMatrix);
  44198. this.bindOnlyNormalMatrix(this._normalMatrix);
  44199. }
  44200. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44201. // Bones
  44202. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44203. var reflectionTexture = null;
  44204. if (mustRebind) {
  44205. this._uniformBuffer.bindToEffect(effect, "Material");
  44206. this.bindViewProjection(effect);
  44207. reflectionTexture = this._getReflectionTexture();
  44208. var refractionTexture = this._getRefractionTexture();
  44209. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44210. // Texture uniforms
  44211. if (scene.texturesEnabled) {
  44212. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44213. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44214. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44215. }
  44216. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44217. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44218. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44219. }
  44220. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44221. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44222. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44223. }
  44224. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44225. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44226. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44227. if (reflectionTexture.boundingBoxSize) {
  44228. var cubeTexture = reflectionTexture;
  44229. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44230. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44231. }
  44232. var polynomials = reflectionTexture.sphericalPolynomial;
  44233. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44234. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44235. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44236. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44237. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44238. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44239. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44240. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44241. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44242. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44243. }
  44244. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44245. }
  44246. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44247. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44248. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44249. }
  44250. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44251. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44252. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44253. }
  44254. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44255. if (this._metallicTexture) {
  44256. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44257. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44258. }
  44259. else if (this._reflectivityTexture) {
  44260. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44261. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44262. }
  44263. if (this._microSurfaceTexture) {
  44264. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44265. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44266. }
  44267. }
  44268. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44269. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44270. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44271. if (scene._mirroredCameraPosition) {
  44272. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44273. }
  44274. else {
  44275. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44276. }
  44277. }
  44278. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44279. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44280. var depth = 1.0;
  44281. if (!refractionTexture.isCube) {
  44282. if (refractionTexture.depth) {
  44283. depth = refractionTexture.depth;
  44284. }
  44285. }
  44286. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44287. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44288. }
  44289. }
  44290. // Point size
  44291. if (this.pointsCloud) {
  44292. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44293. }
  44294. // Colors
  44295. if (defines.METALLICWORKFLOW) {
  44296. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44297. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44298. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44299. }
  44300. else {
  44301. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44302. }
  44303. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44304. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44305. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44306. // Misc
  44307. this._lightingInfos.x = this._directIntensity;
  44308. this._lightingInfos.y = this._emissiveIntensity;
  44309. this._lightingInfos.z = this._environmentIntensity;
  44310. this._lightingInfos.w = this._specularIntensity;
  44311. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44312. }
  44313. // Textures
  44314. if (scene.texturesEnabled) {
  44315. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44316. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44317. }
  44318. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44319. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44320. }
  44321. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44322. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44323. }
  44324. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44325. if (defines.LODBASEDMICROSFURACE) {
  44326. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44327. }
  44328. else {
  44329. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44330. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44331. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44332. }
  44333. }
  44334. if (defines.ENVIRONMENTBRDF) {
  44335. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44336. }
  44337. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44338. if (defines.LODBASEDMICROSFURACE) {
  44339. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44340. }
  44341. else {
  44342. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44343. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44344. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44345. }
  44346. }
  44347. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44348. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44349. }
  44350. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44351. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44352. }
  44353. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44354. if (this._metallicTexture) {
  44355. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44356. }
  44357. else if (this._reflectivityTexture) {
  44358. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44359. }
  44360. if (this._microSurfaceTexture) {
  44361. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44362. }
  44363. }
  44364. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44365. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44366. }
  44367. }
  44368. // Clip plane
  44369. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44370. // Colors
  44371. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44372. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44373. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44374. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44375. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44376. }
  44377. if (mustRebind || !this.isFrozen) {
  44378. // Lights
  44379. if (scene.lightsEnabled && !this._disableLighting) {
  44380. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44381. }
  44382. // View
  44383. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44384. this.bindView(effect);
  44385. }
  44386. // Fog
  44387. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44388. // Morph targets
  44389. if (defines.NUM_MORPH_INFLUENCERS) {
  44390. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44391. }
  44392. // image processing
  44393. this._imageProcessingConfiguration.bind(this._activeEffect);
  44394. // Log. depth
  44395. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44396. }
  44397. this._uniformBuffer.update();
  44398. this._afterBind(mesh, this._activeEffect);
  44399. };
  44400. /**
  44401. * Returns the animatable textures.
  44402. * @returns - Array of animatable textures.
  44403. */
  44404. PBRBaseMaterial.prototype.getAnimatables = function () {
  44405. var results = [];
  44406. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44407. results.push(this._albedoTexture);
  44408. }
  44409. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44410. results.push(this._ambientTexture);
  44411. }
  44412. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44413. results.push(this._opacityTexture);
  44414. }
  44415. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44416. results.push(this._reflectionTexture);
  44417. }
  44418. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44419. results.push(this._emissiveTexture);
  44420. }
  44421. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44422. results.push(this._metallicTexture);
  44423. }
  44424. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44425. results.push(this._reflectivityTexture);
  44426. }
  44427. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44428. results.push(this._bumpTexture);
  44429. }
  44430. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44431. results.push(this._lightmapTexture);
  44432. }
  44433. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44434. results.push(this._refractionTexture);
  44435. }
  44436. return results;
  44437. };
  44438. /**
  44439. * Returns the texture used for reflections.
  44440. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44441. */
  44442. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44443. if (this._reflectionTexture) {
  44444. return this._reflectionTexture;
  44445. }
  44446. return this.getScene().environmentTexture;
  44447. };
  44448. /**
  44449. * Returns the texture used for refraction or null if none is used.
  44450. * @returns - Refection texture if present. If no refraction texture and refraction
  44451. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44452. */
  44453. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44454. if (this._refractionTexture) {
  44455. return this._refractionTexture;
  44456. }
  44457. if (this._linkRefractionWithTransparency) {
  44458. return this.getScene().environmentTexture;
  44459. }
  44460. return null;
  44461. };
  44462. /**
  44463. * Disposes the resources of the material.
  44464. * @param forceDisposeEffect - Forces the disposal of effects.
  44465. * @param forceDisposeTextures - Forces the disposal of all textures.
  44466. */
  44467. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44468. if (forceDisposeTextures) {
  44469. if (this._albedoTexture) {
  44470. this._albedoTexture.dispose();
  44471. }
  44472. if (this._ambientTexture) {
  44473. this._ambientTexture.dispose();
  44474. }
  44475. if (this._opacityTexture) {
  44476. this._opacityTexture.dispose();
  44477. }
  44478. if (this._reflectionTexture) {
  44479. this._reflectionTexture.dispose();
  44480. }
  44481. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44482. this._environmentBRDFTexture.dispose();
  44483. }
  44484. if (this._emissiveTexture) {
  44485. this._emissiveTexture.dispose();
  44486. }
  44487. if (this._metallicTexture) {
  44488. this._metallicTexture.dispose();
  44489. }
  44490. if (this._reflectivityTexture) {
  44491. this._reflectivityTexture.dispose();
  44492. }
  44493. if (this._bumpTexture) {
  44494. this._bumpTexture.dispose();
  44495. }
  44496. if (this._lightmapTexture) {
  44497. this._lightmapTexture.dispose();
  44498. }
  44499. if (this._refractionTexture) {
  44500. this._refractionTexture.dispose();
  44501. }
  44502. }
  44503. this._renderTargets.dispose();
  44504. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44505. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44506. }
  44507. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44508. };
  44509. /**
  44510. * Stores the reflectivity values based on metallic roughness workflow.
  44511. */
  44512. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44513. __decorate([
  44514. BABYLON.serializeAsImageProcessingConfiguration()
  44515. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44516. __decorate([
  44517. BABYLON.serialize()
  44518. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44519. __decorate([
  44520. BABYLON.serialize()
  44521. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44522. return PBRBaseMaterial;
  44523. }(BABYLON.PushMaterial));
  44524. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44525. })(BABYLON || (BABYLON = {}));
  44526. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44527. var BABYLON;
  44528. (function (BABYLON) {
  44529. /**
  44530. * The Physically based simple base material of BJS.
  44531. *
  44532. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44533. * It is used as the base class for both the specGloss and metalRough conventions.
  44534. */
  44535. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44536. __extends(PBRBaseSimpleMaterial, _super);
  44537. /**
  44538. * Instantiates a new PBRMaterial instance.
  44539. *
  44540. * @param name The material name
  44541. * @param scene The scene the material will be use in.
  44542. */
  44543. function PBRBaseSimpleMaterial(name, scene) {
  44544. var _this = _super.call(this, name, scene) || this;
  44545. /**
  44546. * Number of Simultaneous lights allowed on the material.
  44547. */
  44548. _this.maxSimultaneousLights = 4;
  44549. /**
  44550. * If sets to true, disables all the lights affecting the material.
  44551. */
  44552. _this.disableLighting = false;
  44553. /**
  44554. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44555. */
  44556. _this.invertNormalMapX = false;
  44557. /**
  44558. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44559. */
  44560. _this.invertNormalMapY = false;
  44561. /**
  44562. * Emissivie color used to self-illuminate the model.
  44563. */
  44564. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44565. /**
  44566. * Occlusion Channel Strenght.
  44567. */
  44568. _this.occlusionStrength = 1.0;
  44569. _this.useLightmapAsShadowmap = false;
  44570. _this._useAlphaFromAlbedoTexture = true;
  44571. _this._useAmbientInGrayScale = true;
  44572. return _this;
  44573. }
  44574. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44575. /**
  44576. * Gets the current double sided mode.
  44577. */
  44578. get: function () {
  44579. return this._twoSidedLighting;
  44580. },
  44581. /**
  44582. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44583. */
  44584. set: function (value) {
  44585. if (this._twoSidedLighting === value) {
  44586. return;
  44587. }
  44588. this._twoSidedLighting = value;
  44589. this.backFaceCulling = !value;
  44590. this._markAllSubMeshesAsTexturesDirty();
  44591. },
  44592. enumerable: true,
  44593. configurable: true
  44594. });
  44595. /**
  44596. * Return the active textures of the material.
  44597. */
  44598. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44599. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44600. if (this.environmentTexture) {
  44601. activeTextures.push(this.environmentTexture);
  44602. }
  44603. if (this.normalTexture) {
  44604. activeTextures.push(this.normalTexture);
  44605. }
  44606. if (this.emissiveTexture) {
  44607. activeTextures.push(this.emissiveTexture);
  44608. }
  44609. if (this.occlusionTexture) {
  44610. activeTextures.push(this.occlusionTexture);
  44611. }
  44612. if (this.lightmapTexture) {
  44613. activeTextures.push(this.lightmapTexture);
  44614. }
  44615. return activeTextures;
  44616. };
  44617. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44618. if (_super.prototype.hasTexture.call(this, texture)) {
  44619. return true;
  44620. }
  44621. if (this.lightmapTexture === texture) {
  44622. return true;
  44623. }
  44624. return false;
  44625. };
  44626. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44627. return "PBRBaseSimpleMaterial";
  44628. };
  44629. __decorate([
  44630. BABYLON.serialize(),
  44631. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44632. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44633. __decorate([
  44634. BABYLON.serialize(),
  44635. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44636. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44637. __decorate([
  44638. BABYLON.serializeAsTexture(),
  44639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44640. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44641. __decorate([
  44642. BABYLON.serialize(),
  44643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44644. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44645. __decorate([
  44646. BABYLON.serialize(),
  44647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44648. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44649. __decorate([
  44650. BABYLON.serializeAsTexture(),
  44651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44652. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44653. __decorate([
  44654. BABYLON.serializeAsColor3("emissive"),
  44655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44656. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44657. __decorate([
  44658. BABYLON.serializeAsTexture(),
  44659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44660. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44661. __decorate([
  44662. BABYLON.serialize(),
  44663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44664. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44665. __decorate([
  44666. BABYLON.serializeAsTexture(),
  44667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44668. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44669. __decorate([
  44670. BABYLON.serialize(),
  44671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44672. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44673. __decorate([
  44674. BABYLON.serialize()
  44675. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44676. __decorate([
  44677. BABYLON.serializeAsTexture(),
  44678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44679. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44680. __decorate([
  44681. BABYLON.serialize(),
  44682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44683. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44684. return PBRBaseSimpleMaterial;
  44685. }(BABYLON.PBRBaseMaterial));
  44686. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44687. })(BABYLON || (BABYLON = {}));
  44688. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44689. var BABYLON;
  44690. (function (BABYLON) {
  44691. /**
  44692. * The Physically based material of BJS.
  44693. *
  44694. * This offers the main features of a standard PBR material.
  44695. * For more information, please refer to the documentation :
  44696. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44697. */
  44698. var PBRMaterial = /** @class */ (function (_super) {
  44699. __extends(PBRMaterial, _super);
  44700. /**
  44701. * Instantiates a new PBRMaterial instance.
  44702. *
  44703. * @param name The material name
  44704. * @param scene The scene the material will be use in.
  44705. */
  44706. function PBRMaterial(name, scene) {
  44707. var _this = _super.call(this, name, scene) || this;
  44708. /**
  44709. * Intensity of the direct lights e.g. the four lights available in your scene.
  44710. * This impacts both the direct diffuse and specular highlights.
  44711. */
  44712. _this.directIntensity = 1.0;
  44713. /**
  44714. * Intensity of the emissive part of the material.
  44715. * This helps controlling the emissive effect without modifying the emissive color.
  44716. */
  44717. _this.emissiveIntensity = 1.0;
  44718. /**
  44719. * Intensity of the environment e.g. how much the environment will light the object
  44720. * either through harmonics for rough material or through the refelction for shiny ones.
  44721. */
  44722. _this.environmentIntensity = 1.0;
  44723. /**
  44724. * This is a special control allowing the reduction of the specular highlights coming from the
  44725. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44726. */
  44727. _this.specularIntensity = 1.0;
  44728. /**
  44729. * Debug Control allowing disabling the bump map on this material.
  44730. */
  44731. _this.disableBumpMap = false;
  44732. /**
  44733. * AKA Occlusion Texture Intensity in other nomenclature.
  44734. */
  44735. _this.ambientTextureStrength = 1.0;
  44736. /**
  44737. * The color of a material in ambient lighting.
  44738. */
  44739. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44740. /**
  44741. * AKA Diffuse Color in other nomenclature.
  44742. */
  44743. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44744. /**
  44745. * AKA Specular Color in other nomenclature.
  44746. */
  44747. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44748. /**
  44749. * The color reflected from the material.
  44750. */
  44751. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44752. /**
  44753. * The color emitted from the material.
  44754. */
  44755. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44756. /**
  44757. * AKA Glossiness in other nomenclature.
  44758. */
  44759. _this.microSurface = 1.0;
  44760. /**
  44761. * source material index of refraction (IOR)' / 'destination material IOR.
  44762. */
  44763. _this.indexOfRefraction = 0.66;
  44764. /**
  44765. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44766. */
  44767. _this.invertRefractionY = false;
  44768. /**
  44769. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44770. * Materials half opaque for instance using refraction could benefit from this control.
  44771. */
  44772. _this.linkRefractionWithTransparency = false;
  44773. _this.useLightmapAsShadowmap = false;
  44774. /**
  44775. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44776. */
  44777. _this.useAlphaFromAlbedoTexture = false;
  44778. /**
  44779. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44780. */
  44781. _this.forceAlphaTest = false;
  44782. /**
  44783. * Defines the alpha limits in alpha test mode.
  44784. */
  44785. _this.alphaCutOff = 0.4;
  44786. /**
  44787. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44788. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44789. */
  44790. _this.useSpecularOverAlpha = true;
  44791. /**
  44792. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44793. */
  44794. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44795. /**
  44796. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44797. */
  44798. _this.useRoughnessFromMetallicTextureAlpha = true;
  44799. /**
  44800. * Specifies if the metallic texture contains the roughness information in its green channel.
  44801. */
  44802. _this.useRoughnessFromMetallicTextureGreen = false;
  44803. /**
  44804. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44805. */
  44806. _this.useMetallnessFromMetallicTextureBlue = false;
  44807. /**
  44808. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44809. */
  44810. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44811. /**
  44812. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44813. */
  44814. _this.useAmbientInGrayScale = false;
  44815. /**
  44816. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44817. * The material will try to infer what glossiness each pixel should be.
  44818. */
  44819. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44820. /**
  44821. * BJS is using an harcoded light falloff based on a manually sets up range.
  44822. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44823. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44824. */
  44825. _this.usePhysicalLightFalloff = true;
  44826. /**
  44827. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44828. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44829. */
  44830. _this.useRadianceOverAlpha = true;
  44831. /**
  44832. * Allows using an object space normal map (instead of tangent space).
  44833. */
  44834. _this.useObjectSpaceNormalMap = false;
  44835. /**
  44836. * Allows using the bump map in parallax mode.
  44837. */
  44838. _this.useParallax = false;
  44839. /**
  44840. * Allows using the bump map in parallax occlusion mode.
  44841. */
  44842. _this.useParallaxOcclusion = false;
  44843. /**
  44844. * Controls the scale bias of the parallax mode.
  44845. */
  44846. _this.parallaxScaleBias = 0.05;
  44847. /**
  44848. * If sets to true, disables all the lights affecting the material.
  44849. */
  44850. _this.disableLighting = false;
  44851. /**
  44852. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44853. */
  44854. _this.forceIrradianceInFragment = false;
  44855. /**
  44856. * Number of Simultaneous lights allowed on the material.
  44857. */
  44858. _this.maxSimultaneousLights = 4;
  44859. /**
  44860. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44861. */
  44862. _this.invertNormalMapX = false;
  44863. /**
  44864. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44865. */
  44866. _this.invertNormalMapY = false;
  44867. /**
  44868. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44869. */
  44870. _this.twoSidedLighting = false;
  44871. /**
  44872. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44873. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44874. */
  44875. _this.useAlphaFresnel = false;
  44876. /**
  44877. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44878. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44879. */
  44880. _this.useLinearAlphaFresnel = false;
  44881. /**
  44882. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44883. * And/Or occlude the blended part.
  44884. */
  44885. _this.environmentBRDFTexture = null;
  44886. /**
  44887. * Force normal to face away from face.
  44888. */
  44889. _this.forceNormalForward = false;
  44890. /**
  44891. * Enables specular anti aliasing in the PBR shader.
  44892. * It will both interacts on the Geometry for analytical and IBL lighting.
  44893. * It also prefilter the roughness map based on the bump values.
  44894. */
  44895. _this.enableSpecularAntiAliasing = false;
  44896. /**
  44897. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44898. * makes the reflect vector face the model (under horizon).
  44899. */
  44900. _this.useHorizonOcclusion = true;
  44901. /**
  44902. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44903. * too much the area relying on ambient texture to define their ambient occlusion.
  44904. */
  44905. _this.useRadianceOcclusion = true;
  44906. /**
  44907. * If set to true, no lighting calculations will be applied.
  44908. */
  44909. _this.unlit = false;
  44910. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44911. return _this;
  44912. }
  44913. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44914. /**
  44915. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44916. */
  44917. get: function () {
  44918. return this._PBRMATERIAL_OPAQUE;
  44919. },
  44920. enumerable: true,
  44921. configurable: true
  44922. });
  44923. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44924. /**
  44925. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44926. */
  44927. get: function () {
  44928. return this._PBRMATERIAL_ALPHATEST;
  44929. },
  44930. enumerable: true,
  44931. configurable: true
  44932. });
  44933. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44934. /**
  44935. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44936. */
  44937. get: function () {
  44938. return this._PBRMATERIAL_ALPHABLEND;
  44939. },
  44940. enumerable: true,
  44941. configurable: true
  44942. });
  44943. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44944. /**
  44945. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44946. * They are also discarded below the alpha cutoff threshold to improve performances.
  44947. */
  44948. get: function () {
  44949. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44950. },
  44951. enumerable: true,
  44952. configurable: true
  44953. });
  44954. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44955. /**
  44956. * Gets the image processing configuration used either in this material.
  44957. */
  44958. get: function () {
  44959. return this._imageProcessingConfiguration;
  44960. },
  44961. /**
  44962. * Sets the Default image processing configuration used either in the this material.
  44963. *
  44964. * If sets to null, the scene one is in use.
  44965. */
  44966. set: function (value) {
  44967. this._attachImageProcessingConfiguration(value);
  44968. // Ensure the effect will be rebuilt.
  44969. this._markAllSubMeshesAsTexturesDirty();
  44970. },
  44971. enumerable: true,
  44972. configurable: true
  44973. });
  44974. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44975. /**
  44976. * Gets wether the color curves effect is enabled.
  44977. */
  44978. get: function () {
  44979. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44980. },
  44981. /**
  44982. * Sets wether the color curves effect is enabled.
  44983. */
  44984. set: function (value) {
  44985. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44986. },
  44987. enumerable: true,
  44988. configurable: true
  44989. });
  44990. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44991. /**
  44992. * Gets wether the color grading effect is enabled.
  44993. */
  44994. get: function () {
  44995. return this.imageProcessingConfiguration.colorGradingEnabled;
  44996. },
  44997. /**
  44998. * Gets wether the color grading effect is enabled.
  44999. */
  45000. set: function (value) {
  45001. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45002. },
  45003. enumerable: true,
  45004. configurable: true
  45005. });
  45006. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45007. /**
  45008. * Gets wether tonemapping is enabled or not.
  45009. */
  45010. get: function () {
  45011. return this._imageProcessingConfiguration.toneMappingEnabled;
  45012. },
  45013. /**
  45014. * Sets wether tonemapping is enabled or not
  45015. */
  45016. set: function (value) {
  45017. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45018. },
  45019. enumerable: true,
  45020. configurable: true
  45021. });
  45022. ;
  45023. ;
  45024. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45025. /**
  45026. * The camera exposure used on this material.
  45027. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45028. * This corresponds to a photographic exposure.
  45029. */
  45030. get: function () {
  45031. return this._imageProcessingConfiguration.exposure;
  45032. },
  45033. /**
  45034. * The camera exposure used on this material.
  45035. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45036. * This corresponds to a photographic exposure.
  45037. */
  45038. set: function (value) {
  45039. this._imageProcessingConfiguration.exposure = value;
  45040. },
  45041. enumerable: true,
  45042. configurable: true
  45043. });
  45044. ;
  45045. ;
  45046. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45047. /**
  45048. * Gets The camera contrast used on this material.
  45049. */
  45050. get: function () {
  45051. return this._imageProcessingConfiguration.contrast;
  45052. },
  45053. /**
  45054. * Sets The camera contrast used on this material.
  45055. */
  45056. set: function (value) {
  45057. this._imageProcessingConfiguration.contrast = value;
  45058. },
  45059. enumerable: true,
  45060. configurable: true
  45061. });
  45062. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45063. /**
  45064. * Gets the Color Grading 2D Lookup Texture.
  45065. */
  45066. get: function () {
  45067. return this._imageProcessingConfiguration.colorGradingTexture;
  45068. },
  45069. /**
  45070. * Sets the Color Grading 2D Lookup Texture.
  45071. */
  45072. set: function (value) {
  45073. this._imageProcessingConfiguration.colorGradingTexture = value;
  45074. },
  45075. enumerable: true,
  45076. configurable: true
  45077. });
  45078. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45079. /**
  45080. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45081. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45082. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  45083. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45084. */
  45085. get: function () {
  45086. return this._imageProcessingConfiguration.colorCurves;
  45087. },
  45088. /**
  45089. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45090. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45091. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  45092. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45093. */
  45094. set: function (value) {
  45095. this._imageProcessingConfiguration.colorCurves = value;
  45096. },
  45097. enumerable: true,
  45098. configurable: true
  45099. });
  45100. /**
  45101. * Returns the name of this material class.
  45102. */
  45103. PBRMaterial.prototype.getClassName = function () {
  45104. return "PBRMaterial";
  45105. };
  45106. /**
  45107. * Returns an array of the actively used textures.
  45108. * @returns - Array of BaseTextures
  45109. */
  45110. PBRMaterial.prototype.getActiveTextures = function () {
  45111. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45112. if (this._albedoTexture) {
  45113. activeTextures.push(this._albedoTexture);
  45114. }
  45115. if (this._ambientTexture) {
  45116. activeTextures.push(this._ambientTexture);
  45117. }
  45118. if (this._opacityTexture) {
  45119. activeTextures.push(this._opacityTexture);
  45120. }
  45121. if (this._reflectionTexture) {
  45122. activeTextures.push(this._reflectionTexture);
  45123. }
  45124. if (this._emissiveTexture) {
  45125. activeTextures.push(this._emissiveTexture);
  45126. }
  45127. if (this._reflectivityTexture) {
  45128. activeTextures.push(this._reflectivityTexture);
  45129. }
  45130. if (this._metallicTexture) {
  45131. activeTextures.push(this._metallicTexture);
  45132. }
  45133. if (this._microSurfaceTexture) {
  45134. activeTextures.push(this._microSurfaceTexture);
  45135. }
  45136. if (this._bumpTexture) {
  45137. activeTextures.push(this._bumpTexture);
  45138. }
  45139. if (this._lightmapTexture) {
  45140. activeTextures.push(this._lightmapTexture);
  45141. }
  45142. if (this._refractionTexture) {
  45143. activeTextures.push(this._refractionTexture);
  45144. }
  45145. return activeTextures;
  45146. };
  45147. /**
  45148. * Checks to see if a texture is used in the material.
  45149. * @param texture - Base texture to use.
  45150. * @returns - Boolean specifying if a texture is used in the material.
  45151. */
  45152. PBRMaterial.prototype.hasTexture = function (texture) {
  45153. if (_super.prototype.hasTexture.call(this, texture)) {
  45154. return true;
  45155. }
  45156. if (this._albedoTexture === texture) {
  45157. return true;
  45158. }
  45159. if (this._ambientTexture === texture) {
  45160. return true;
  45161. }
  45162. if (this._opacityTexture === texture) {
  45163. return true;
  45164. }
  45165. if (this._reflectionTexture === texture) {
  45166. return true;
  45167. }
  45168. if (this._reflectivityTexture === texture) {
  45169. return true;
  45170. }
  45171. if (this._metallicTexture === texture) {
  45172. return true;
  45173. }
  45174. if (this._microSurfaceTexture === texture) {
  45175. return true;
  45176. }
  45177. if (this._bumpTexture === texture) {
  45178. return true;
  45179. }
  45180. if (this._lightmapTexture === texture) {
  45181. return true;
  45182. }
  45183. if (this._refractionTexture === texture) {
  45184. return true;
  45185. }
  45186. return false;
  45187. };
  45188. /**
  45189. * Makes a duplicate of the current material.
  45190. * @param name - name to use for the new material.
  45191. */
  45192. PBRMaterial.prototype.clone = function (name) {
  45193. var _this = this;
  45194. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45195. clone.id = name;
  45196. clone.name = name;
  45197. return clone;
  45198. };
  45199. /**
  45200. * Serializes this PBR Material.
  45201. * @returns - An object with the serialized material.
  45202. */
  45203. PBRMaterial.prototype.serialize = function () {
  45204. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45205. serializationObject.customType = "BABYLON.PBRMaterial";
  45206. return serializationObject;
  45207. };
  45208. // Statics
  45209. /**
  45210. * Parses a PBR Material from a serialized object.
  45211. * @param source - Serialized object.
  45212. * @param scene - BJS scene instance.
  45213. * @param rootUrl - url for the scene object
  45214. * @returns - PBRMaterial
  45215. */
  45216. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45217. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45218. };
  45219. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45220. /**
  45221. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45222. */
  45223. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45224. /**
  45225. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45226. */
  45227. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45228. /**
  45229. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45230. * They are also discarded below the alpha cutoff threshold to improve performances.
  45231. */
  45232. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45233. __decorate([
  45234. BABYLON.serialize(),
  45235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45236. ], PBRMaterial.prototype, "directIntensity", void 0);
  45237. __decorate([
  45238. BABYLON.serialize(),
  45239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45240. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45241. __decorate([
  45242. BABYLON.serialize(),
  45243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45244. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45245. __decorate([
  45246. BABYLON.serialize(),
  45247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45248. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45249. __decorate([
  45250. BABYLON.serialize(),
  45251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45252. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45253. __decorate([
  45254. BABYLON.serializeAsTexture(),
  45255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45256. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45257. __decorate([
  45258. BABYLON.serializeAsTexture(),
  45259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45260. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45261. __decorate([
  45262. BABYLON.serialize(),
  45263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45264. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45265. __decorate([
  45266. BABYLON.serializeAsTexture(),
  45267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45268. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45269. __decorate([
  45270. BABYLON.serializeAsTexture(),
  45271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45272. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45273. __decorate([
  45274. BABYLON.serializeAsTexture(),
  45275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45276. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45277. __decorate([
  45278. BABYLON.serializeAsTexture(),
  45279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45280. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45281. __decorate([
  45282. BABYLON.serializeAsTexture(),
  45283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45284. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45285. __decorate([
  45286. BABYLON.serialize(),
  45287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45288. ], PBRMaterial.prototype, "metallic", void 0);
  45289. __decorate([
  45290. BABYLON.serialize(),
  45291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45292. ], PBRMaterial.prototype, "roughness", void 0);
  45293. __decorate([
  45294. BABYLON.serializeAsTexture(),
  45295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45296. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45297. __decorate([
  45298. BABYLON.serializeAsTexture(),
  45299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45300. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45301. __decorate([
  45302. BABYLON.serializeAsTexture(),
  45303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45304. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45305. __decorate([
  45306. BABYLON.serializeAsTexture(),
  45307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45308. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45309. __decorate([
  45310. BABYLON.serializeAsColor3("ambient"),
  45311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45312. ], PBRMaterial.prototype, "ambientColor", void 0);
  45313. __decorate([
  45314. BABYLON.serializeAsColor3("albedo"),
  45315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45316. ], PBRMaterial.prototype, "albedoColor", void 0);
  45317. __decorate([
  45318. BABYLON.serializeAsColor3("reflectivity"),
  45319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45320. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45321. __decorate([
  45322. BABYLON.serializeAsColor3("reflection"),
  45323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45324. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45325. __decorate([
  45326. BABYLON.serializeAsColor3("emissive"),
  45327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45328. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45329. __decorate([
  45330. BABYLON.serialize(),
  45331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45332. ], PBRMaterial.prototype, "microSurface", void 0);
  45333. __decorate([
  45334. BABYLON.serialize(),
  45335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45336. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45337. __decorate([
  45338. BABYLON.serialize(),
  45339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45340. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45341. __decorate([
  45342. BABYLON.serialize(),
  45343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45344. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45345. __decorate([
  45346. BABYLON.serialize(),
  45347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45348. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45349. __decorate([
  45350. BABYLON.serialize(),
  45351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45352. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45353. __decorate([
  45354. BABYLON.serialize(),
  45355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45356. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45357. __decorate([
  45358. BABYLON.serialize(),
  45359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45360. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45361. __decorate([
  45362. BABYLON.serialize(),
  45363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45364. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45365. __decorate([
  45366. BABYLON.serialize(),
  45367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45368. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45369. __decorate([
  45370. BABYLON.serialize(),
  45371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45372. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45373. __decorate([
  45374. BABYLON.serialize(),
  45375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45376. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45377. __decorate([
  45378. BABYLON.serialize(),
  45379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45380. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45381. __decorate([
  45382. BABYLON.serialize(),
  45383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45384. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45385. __decorate([
  45386. BABYLON.serialize(),
  45387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45388. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45389. __decorate([
  45390. BABYLON.serialize(),
  45391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45392. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45393. __decorate([
  45394. BABYLON.serialize(),
  45395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45396. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45397. __decorate([
  45398. BABYLON.serialize(),
  45399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45400. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45401. __decorate([
  45402. BABYLON.serialize(),
  45403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45404. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45405. __decorate([
  45406. BABYLON.serialize(),
  45407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45408. ], PBRMaterial.prototype, "useParallax", void 0);
  45409. __decorate([
  45410. BABYLON.serialize(),
  45411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45412. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45413. __decorate([
  45414. BABYLON.serialize(),
  45415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45416. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45417. __decorate([
  45418. BABYLON.serialize(),
  45419. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45420. ], PBRMaterial.prototype, "disableLighting", void 0);
  45421. __decorate([
  45422. BABYLON.serialize(),
  45423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45424. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45425. __decorate([
  45426. BABYLON.serialize(),
  45427. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45428. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45429. __decorate([
  45430. BABYLON.serialize(),
  45431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45432. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45433. __decorate([
  45434. BABYLON.serialize(),
  45435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45436. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45437. __decorate([
  45438. BABYLON.serialize(),
  45439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45440. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45441. __decorate([
  45442. BABYLON.serialize(),
  45443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45444. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45445. __decorate([
  45446. BABYLON.serialize(),
  45447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45448. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45449. __decorate([
  45450. BABYLON.serializeAsTexture(),
  45451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45452. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45453. __decorate([
  45454. BABYLON.serialize(),
  45455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45456. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45457. __decorate([
  45458. BABYLON.serialize(),
  45459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45460. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45461. __decorate([
  45462. BABYLON.serialize(),
  45463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45464. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45465. __decorate([
  45466. BABYLON.serialize(),
  45467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45468. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45469. __decorate([
  45470. BABYLON.serialize(),
  45471. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45472. ], PBRMaterial.prototype, "unlit", void 0);
  45473. return PBRMaterial;
  45474. }(BABYLON.PBRBaseMaterial));
  45475. BABYLON.PBRMaterial = PBRMaterial;
  45476. })(BABYLON || (BABYLON = {}));
  45477. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45478. var BABYLON;
  45479. (function (BABYLON) {
  45480. /**
  45481. * The PBR material of BJS following the metal roughness convention.
  45482. *
  45483. * This fits to the PBR convention in the GLTF definition:
  45484. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45485. */
  45486. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45487. __extends(PBRMetallicRoughnessMaterial, _super);
  45488. /**
  45489. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45490. *
  45491. * @param name The material name
  45492. * @param scene The scene the material will be use in.
  45493. */
  45494. function PBRMetallicRoughnessMaterial(name, scene) {
  45495. var _this = _super.call(this, name, scene) || this;
  45496. _this._useRoughnessFromMetallicTextureAlpha = false;
  45497. _this._useRoughnessFromMetallicTextureGreen = true;
  45498. _this._useMetallnessFromMetallicTextureBlue = true;
  45499. _this.metallic = 1.0;
  45500. _this.roughness = 1.0;
  45501. return _this;
  45502. }
  45503. /**
  45504. * Return the currrent class name of the material.
  45505. */
  45506. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45507. return "PBRMetallicRoughnessMaterial";
  45508. };
  45509. /**
  45510. * Return the active textures of the material.
  45511. */
  45512. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45513. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45514. if (this.baseTexture) {
  45515. activeTextures.push(this.baseTexture);
  45516. }
  45517. if (this.metallicRoughnessTexture) {
  45518. activeTextures.push(this.metallicRoughnessTexture);
  45519. }
  45520. return activeTextures;
  45521. };
  45522. /**
  45523. * Checks to see if a texture is used in the material.
  45524. * @param texture - Base texture to use.
  45525. * @returns - Boolean specifying if a texture is used in the material.
  45526. */
  45527. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45528. if (_super.prototype.hasTexture.call(this, texture)) {
  45529. return true;
  45530. }
  45531. if (this.baseTexture === texture) {
  45532. return true;
  45533. }
  45534. if (this.metallicRoughnessTexture === texture) {
  45535. return true;
  45536. }
  45537. return false;
  45538. };
  45539. /**
  45540. * Makes a duplicate of the current material.
  45541. * @param name - name to use for the new material.
  45542. */
  45543. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45544. var _this = this;
  45545. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45546. clone.id = name;
  45547. clone.name = name;
  45548. return clone;
  45549. };
  45550. /**
  45551. * Serialize the material to a parsable JSON object.
  45552. */
  45553. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45554. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45555. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45556. return serializationObject;
  45557. };
  45558. /**
  45559. * Parses a JSON object correponding to the serialize function.
  45560. */
  45561. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45562. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45563. };
  45564. __decorate([
  45565. BABYLON.serializeAsColor3(),
  45566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45567. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45568. __decorate([
  45569. BABYLON.serializeAsTexture(),
  45570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45571. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45572. __decorate([
  45573. BABYLON.serialize(),
  45574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45575. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45576. __decorate([
  45577. BABYLON.serialize(),
  45578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45579. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45580. __decorate([
  45581. BABYLON.serializeAsTexture(),
  45582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45583. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45584. return PBRMetallicRoughnessMaterial;
  45585. }(BABYLON.PBRBaseSimpleMaterial));
  45586. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45587. })(BABYLON || (BABYLON = {}));
  45588. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45589. var BABYLON;
  45590. (function (BABYLON) {
  45591. /**
  45592. * The PBR material of BJS following the specular glossiness convention.
  45593. *
  45594. * This fits to the PBR convention in the GLTF definition:
  45595. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45596. */
  45597. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45598. __extends(PBRSpecularGlossinessMaterial, _super);
  45599. /**
  45600. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45601. *
  45602. * @param name The material name
  45603. * @param scene The scene the material will be use in.
  45604. */
  45605. function PBRSpecularGlossinessMaterial(name, scene) {
  45606. var _this = _super.call(this, name, scene) || this;
  45607. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45608. return _this;
  45609. }
  45610. /**
  45611. * Return the currrent class name of the material.
  45612. */
  45613. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45614. return "PBRSpecularGlossinessMaterial";
  45615. };
  45616. /**
  45617. * Return the active textures of the material.
  45618. */
  45619. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45620. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45621. if (this.diffuseTexture) {
  45622. activeTextures.push(this.diffuseTexture);
  45623. }
  45624. if (this.specularGlossinessTexture) {
  45625. activeTextures.push(this.specularGlossinessTexture);
  45626. }
  45627. return activeTextures;
  45628. };
  45629. /**
  45630. * Checks to see if a texture is used in the material.
  45631. * @param texture - Base texture to use.
  45632. * @returns - Boolean specifying if a texture is used in the material.
  45633. */
  45634. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45635. if (_super.prototype.hasTexture.call(this, texture)) {
  45636. return true;
  45637. }
  45638. if (this.diffuseTexture === texture) {
  45639. return true;
  45640. }
  45641. if (this.specularGlossinessTexture === texture) {
  45642. return true;
  45643. }
  45644. return false;
  45645. };
  45646. /**
  45647. * Makes a duplicate of the current material.
  45648. * @param name - name to use for the new material.
  45649. */
  45650. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45651. var _this = this;
  45652. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45653. clone.id = name;
  45654. clone.name = name;
  45655. return clone;
  45656. };
  45657. /**
  45658. * Serialize the material to a parsable JSON object.
  45659. */
  45660. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45661. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45662. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45663. return serializationObject;
  45664. };
  45665. /**
  45666. * Parses a JSON object correponding to the serialize function.
  45667. */
  45668. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45669. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45670. };
  45671. __decorate([
  45672. BABYLON.serializeAsColor3("diffuse"),
  45673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45674. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45675. __decorate([
  45676. BABYLON.serializeAsTexture(),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45678. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45679. __decorate([
  45680. BABYLON.serializeAsColor3("specular"),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45682. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45683. __decorate([
  45684. BABYLON.serialize(),
  45685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45686. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45687. __decorate([
  45688. BABYLON.serializeAsTexture(),
  45689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45690. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45691. return PBRSpecularGlossinessMaterial;
  45692. }(BABYLON.PBRBaseSimpleMaterial));
  45693. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45694. })(BABYLON || (BABYLON = {}));
  45695. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45696. var BABYLON;
  45697. (function (BABYLON) {
  45698. BABYLON.CameraInputTypes = {};
  45699. var CameraInputsManager = /** @class */ (function () {
  45700. function CameraInputsManager(camera) {
  45701. this.attached = {};
  45702. this.camera = camera;
  45703. this.checkInputs = function () { };
  45704. }
  45705. /**
  45706. * Add an input method to a camera
  45707. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45708. * @param input camera input method
  45709. */
  45710. CameraInputsManager.prototype.add = function (input) {
  45711. var type = input.getSimpleName();
  45712. if (this.attached[type]) {
  45713. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45714. return;
  45715. }
  45716. this.attached[type] = input;
  45717. input.camera = this.camera;
  45718. //for checkInputs, we are dynamically creating a function
  45719. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45720. if (input.checkInputs) {
  45721. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45722. }
  45723. if (this.attachedElement) {
  45724. input.attachControl(this.attachedElement);
  45725. }
  45726. };
  45727. /**
  45728. * Remove a specific input method from a camera
  45729. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45730. * @param inputToRemove camera input method
  45731. */
  45732. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45733. for (var cam in this.attached) {
  45734. var input = this.attached[cam];
  45735. if (input === inputToRemove) {
  45736. input.detachControl(this.attachedElement);
  45737. input.camera = null;
  45738. delete this.attached[cam];
  45739. this.rebuildInputCheck();
  45740. }
  45741. }
  45742. };
  45743. CameraInputsManager.prototype.removeByType = function (inputType) {
  45744. for (var cam in this.attached) {
  45745. var input = this.attached[cam];
  45746. if (input.getClassName() === inputType) {
  45747. input.detachControl(this.attachedElement);
  45748. input.camera = null;
  45749. delete this.attached[cam];
  45750. this.rebuildInputCheck();
  45751. }
  45752. }
  45753. };
  45754. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45755. var current = this.checkInputs;
  45756. return function () {
  45757. current();
  45758. fn();
  45759. };
  45760. };
  45761. CameraInputsManager.prototype.attachInput = function (input) {
  45762. if (this.attachedElement) {
  45763. input.attachControl(this.attachedElement, this.noPreventDefault);
  45764. }
  45765. };
  45766. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45767. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45768. if (this.attachedElement) {
  45769. return;
  45770. }
  45771. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45772. this.attachedElement = element;
  45773. this.noPreventDefault = noPreventDefault;
  45774. for (var cam in this.attached) {
  45775. this.attached[cam].attachControl(element, noPreventDefault);
  45776. }
  45777. };
  45778. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45779. if (disconnect === void 0) { disconnect = false; }
  45780. if (this.attachedElement !== element) {
  45781. return;
  45782. }
  45783. for (var cam in this.attached) {
  45784. this.attached[cam].detachControl(element);
  45785. if (disconnect) {
  45786. this.attached[cam].camera = null;
  45787. }
  45788. }
  45789. this.attachedElement = null;
  45790. };
  45791. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45792. this.checkInputs = function () { };
  45793. for (var cam in this.attached) {
  45794. var input = this.attached[cam];
  45795. if (input.checkInputs) {
  45796. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45797. }
  45798. }
  45799. };
  45800. /**
  45801. * Remove all attached input methods from a camera
  45802. */
  45803. CameraInputsManager.prototype.clear = function () {
  45804. if (this.attachedElement) {
  45805. this.detachElement(this.attachedElement, true);
  45806. }
  45807. this.attached = {};
  45808. this.attachedElement = null;
  45809. this.checkInputs = function () { };
  45810. };
  45811. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45812. var inputs = {};
  45813. for (var cam in this.attached) {
  45814. var input = this.attached[cam];
  45815. var res = BABYLON.SerializationHelper.Serialize(input);
  45816. inputs[input.getClassName()] = res;
  45817. }
  45818. serializedCamera.inputsmgr = inputs;
  45819. };
  45820. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45821. var parsedInputs = parsedCamera.inputsmgr;
  45822. if (parsedInputs) {
  45823. this.clear();
  45824. for (var n in parsedInputs) {
  45825. var construct = BABYLON.CameraInputTypes[n];
  45826. if (construct) {
  45827. var parsedinput = parsedInputs[n];
  45828. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45829. this.add(input);
  45830. }
  45831. }
  45832. }
  45833. else {
  45834. //2016-03-08 this part is for managing backward compatibility
  45835. for (var n in this.attached) {
  45836. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45837. if (construct) {
  45838. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45839. this.remove(this.attached[n]);
  45840. this.add(input);
  45841. }
  45842. }
  45843. }
  45844. };
  45845. return CameraInputsManager;
  45846. }());
  45847. BABYLON.CameraInputsManager = CameraInputsManager;
  45848. })(BABYLON || (BABYLON = {}));
  45849. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45850. var BABYLON;
  45851. (function (BABYLON) {
  45852. var TargetCamera = /** @class */ (function (_super) {
  45853. __extends(TargetCamera, _super);
  45854. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45855. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45856. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45857. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45858. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45859. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45860. _this.speed = 2.0;
  45861. _this.noRotationConstraint = false;
  45862. _this.lockedTarget = null;
  45863. _this._currentTarget = BABYLON.Vector3.Zero();
  45864. _this._viewMatrix = BABYLON.Matrix.Zero();
  45865. _this._camMatrix = BABYLON.Matrix.Zero();
  45866. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45867. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45868. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45869. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45870. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45871. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45872. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45873. return _this;
  45874. }
  45875. TargetCamera.prototype.getFrontPosition = function (distance) {
  45876. this.getWorldMatrix();
  45877. var direction = this.getTarget().subtract(this.position);
  45878. direction.normalize();
  45879. direction.scaleInPlace(distance);
  45880. return this.globalPosition.add(direction);
  45881. };
  45882. TargetCamera.prototype._getLockedTargetPosition = function () {
  45883. if (!this.lockedTarget) {
  45884. return null;
  45885. }
  45886. if (this.lockedTarget.absolutePosition) {
  45887. this.lockedTarget.computeWorldMatrix();
  45888. }
  45889. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45890. };
  45891. TargetCamera.prototype.storeState = function () {
  45892. this._storedPosition = this.position.clone();
  45893. this._storedRotation = this.rotation.clone();
  45894. if (this.rotationQuaternion) {
  45895. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45896. }
  45897. return _super.prototype.storeState.call(this);
  45898. };
  45899. /**
  45900. * Restored camera state. You must call storeState() first
  45901. */
  45902. TargetCamera.prototype._restoreStateValues = function () {
  45903. if (!_super.prototype._restoreStateValues.call(this)) {
  45904. return false;
  45905. }
  45906. this.position = this._storedPosition.clone();
  45907. this.rotation = this._storedRotation.clone();
  45908. if (this.rotationQuaternion) {
  45909. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45910. }
  45911. this.cameraDirection.copyFromFloats(0, 0, 0);
  45912. this.cameraRotation.copyFromFloats(0, 0);
  45913. return true;
  45914. };
  45915. // Cache
  45916. TargetCamera.prototype._initCache = function () {
  45917. _super.prototype._initCache.call(this);
  45918. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45919. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45920. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45921. };
  45922. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45923. if (!ignoreParentClass) {
  45924. _super.prototype._updateCache.call(this);
  45925. }
  45926. var lockedTargetPosition = this._getLockedTargetPosition();
  45927. if (!lockedTargetPosition) {
  45928. this._cache.lockedTarget = null;
  45929. }
  45930. else {
  45931. if (!this._cache.lockedTarget) {
  45932. this._cache.lockedTarget = lockedTargetPosition.clone();
  45933. }
  45934. else {
  45935. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45936. }
  45937. }
  45938. this._cache.rotation.copyFrom(this.rotation);
  45939. if (this.rotationQuaternion)
  45940. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45941. };
  45942. // Synchronized
  45943. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45944. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45945. return false;
  45946. }
  45947. var lockedTargetPosition = this._getLockedTargetPosition();
  45948. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45949. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45950. };
  45951. // Methods
  45952. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45953. var engine = this.getEngine();
  45954. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45955. };
  45956. // Target
  45957. TargetCamera.prototype.setTarget = function (target) {
  45958. this.upVector.normalize();
  45959. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45960. this._camMatrix.invert();
  45961. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45962. var vDir = target.subtract(this.position);
  45963. if (vDir.x >= 0.0) {
  45964. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45965. }
  45966. else {
  45967. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45968. }
  45969. this.rotation.z = 0;
  45970. if (isNaN(this.rotation.x)) {
  45971. this.rotation.x = 0;
  45972. }
  45973. if (isNaN(this.rotation.y)) {
  45974. this.rotation.y = 0;
  45975. }
  45976. if (isNaN(this.rotation.z)) {
  45977. this.rotation.z = 0;
  45978. }
  45979. if (this.rotationQuaternion) {
  45980. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45981. }
  45982. };
  45983. /**
  45984. * Return the current target position of the camera. This value is expressed in local space.
  45985. */
  45986. TargetCamera.prototype.getTarget = function () {
  45987. return this._currentTarget;
  45988. };
  45989. TargetCamera.prototype._decideIfNeedsToMove = function () {
  45990. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45991. };
  45992. TargetCamera.prototype._updatePosition = function () {
  45993. if (this.parent) {
  45994. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  45995. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  45996. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  45997. return;
  45998. }
  45999. this.position.addInPlace(this.cameraDirection);
  46000. };
  46001. TargetCamera.prototype._checkInputs = function () {
  46002. var needToMove = this._decideIfNeedsToMove();
  46003. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46004. // Move
  46005. if (needToMove) {
  46006. this._updatePosition();
  46007. }
  46008. // Rotate
  46009. if (needToRotate) {
  46010. this.rotation.x += this.cameraRotation.x;
  46011. this.rotation.y += this.cameraRotation.y;
  46012. //rotate, if quaternion is set and rotation was used
  46013. if (this.rotationQuaternion) {
  46014. var len = this.rotation.lengthSquared();
  46015. if (len) {
  46016. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46017. }
  46018. }
  46019. if (!this.noRotationConstraint) {
  46020. var limit = (Math.PI / 2) * 0.95;
  46021. if (this.rotation.x > limit)
  46022. this.rotation.x = limit;
  46023. if (this.rotation.x < -limit)
  46024. this.rotation.x = -limit;
  46025. }
  46026. }
  46027. // Inertia
  46028. if (needToMove) {
  46029. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46030. this.cameraDirection.x = 0;
  46031. }
  46032. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46033. this.cameraDirection.y = 0;
  46034. }
  46035. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46036. this.cameraDirection.z = 0;
  46037. }
  46038. this.cameraDirection.scaleInPlace(this.inertia);
  46039. }
  46040. if (needToRotate) {
  46041. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46042. this.cameraRotation.x = 0;
  46043. }
  46044. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46045. this.cameraRotation.y = 0;
  46046. }
  46047. this.cameraRotation.scaleInPlace(this.inertia);
  46048. }
  46049. _super.prototype._checkInputs.call(this);
  46050. };
  46051. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46052. if (this.rotationQuaternion) {
  46053. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46054. }
  46055. else {
  46056. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46057. }
  46058. //update the up vector!
  46059. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46060. };
  46061. TargetCamera.prototype._getViewMatrix = function () {
  46062. if (this.lockedTarget) {
  46063. this.setTarget(this._getLockedTargetPosition());
  46064. }
  46065. // Compute
  46066. this._updateCameraRotationMatrix();
  46067. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46068. // Computing target and final matrix
  46069. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46070. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46071. return this._viewMatrix;
  46072. };
  46073. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46074. if (this.parent) {
  46075. var parentWorldMatrix = this.parent.getWorldMatrix();
  46076. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46077. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46078. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46079. this._markSyncedWithParent();
  46080. }
  46081. else {
  46082. this._globalPosition.copyFrom(this.position);
  46083. this._globalCurrentTarget.copyFrom(target);
  46084. this._globalCurrentUpVector.copyFrom(up);
  46085. }
  46086. if (this.getScene().useRightHandedSystem) {
  46087. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46088. }
  46089. else {
  46090. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46091. }
  46092. };
  46093. /**
  46094. * @override
  46095. * Override Camera.createRigCamera
  46096. */
  46097. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46098. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46099. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46100. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46101. if (!this.rotationQuaternion) {
  46102. this.rotationQuaternion = new BABYLON.Quaternion();
  46103. }
  46104. rigCamera._cameraRigParams = {};
  46105. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46106. }
  46107. return rigCamera;
  46108. }
  46109. return null;
  46110. };
  46111. /**
  46112. * @override
  46113. * Override Camera._updateRigCameras
  46114. */
  46115. TargetCamera.prototype._updateRigCameras = function () {
  46116. var camLeft = this._rigCameras[0];
  46117. var camRight = this._rigCameras[1];
  46118. switch (this.cameraRigMode) {
  46119. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46120. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46121. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46122. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46123. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46124. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46125. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46126. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46127. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46128. camLeft.setTarget(this.getTarget());
  46129. camRight.setTarget(this.getTarget());
  46130. break;
  46131. case BABYLON.Camera.RIG_MODE_VR:
  46132. if (camLeft.rotationQuaternion) {
  46133. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46134. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46135. }
  46136. else {
  46137. camLeft.rotation.copyFrom(this.rotation);
  46138. camRight.rotation.copyFrom(this.rotation);
  46139. }
  46140. camLeft.position.copyFrom(this.position);
  46141. camRight.position.copyFrom(this.position);
  46142. break;
  46143. }
  46144. _super.prototype._updateRigCameras.call(this);
  46145. };
  46146. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46147. if (!this._rigCamTransformMatrix) {
  46148. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46149. }
  46150. var target = this.getTarget();
  46151. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46152. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46153. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46154. };
  46155. TargetCamera.prototype.getClassName = function () {
  46156. return "TargetCamera";
  46157. };
  46158. __decorate([
  46159. BABYLON.serializeAsVector3()
  46160. ], TargetCamera.prototype, "rotation", void 0);
  46161. __decorate([
  46162. BABYLON.serialize()
  46163. ], TargetCamera.prototype, "speed", void 0);
  46164. __decorate([
  46165. BABYLON.serializeAsMeshReference("lockedTargetId")
  46166. ], TargetCamera.prototype, "lockedTarget", void 0);
  46167. return TargetCamera;
  46168. }(BABYLON.Camera));
  46169. BABYLON.TargetCamera = TargetCamera;
  46170. })(BABYLON || (BABYLON = {}));
  46171. //# sourceMappingURL=babylon.targetCamera.js.map
  46172. var BABYLON;
  46173. (function (BABYLON) {
  46174. var FreeCameraMouseInput = /** @class */ (function () {
  46175. function FreeCameraMouseInput(touchEnabled) {
  46176. if (touchEnabled === void 0) { touchEnabled = true; }
  46177. this.touchEnabled = touchEnabled;
  46178. this.buttons = [0, 1, 2];
  46179. this.angularSensibility = 2000.0;
  46180. this.previousPosition = null;
  46181. }
  46182. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46183. var _this = this;
  46184. var engine = this.camera.getEngine();
  46185. if (!this._pointerInput) {
  46186. this._pointerInput = function (p, s) {
  46187. var evt = p.event;
  46188. if (engine.isInVRExclusivePointerMode) {
  46189. return;
  46190. }
  46191. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46192. return;
  46193. }
  46194. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46195. return;
  46196. }
  46197. var srcElement = (evt.srcElement || evt.target);
  46198. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46199. try {
  46200. srcElement.setPointerCapture(evt.pointerId);
  46201. }
  46202. catch (e) {
  46203. //Nothing to do with the error. Execution will continue.
  46204. }
  46205. _this.previousPosition = {
  46206. x: evt.clientX,
  46207. y: evt.clientY
  46208. };
  46209. if (!noPreventDefault) {
  46210. evt.preventDefault();
  46211. element.focus();
  46212. }
  46213. }
  46214. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46215. try {
  46216. srcElement.releasePointerCapture(evt.pointerId);
  46217. }
  46218. catch (e) {
  46219. //Nothing to do with the error.
  46220. }
  46221. _this.previousPosition = null;
  46222. if (!noPreventDefault) {
  46223. evt.preventDefault();
  46224. }
  46225. }
  46226. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46227. if (!_this.previousPosition || engine.isPointerLock) {
  46228. return;
  46229. }
  46230. var offsetX = evt.clientX - _this.previousPosition.x;
  46231. if (_this.camera.getScene().useRightHandedSystem)
  46232. offsetX *= -1;
  46233. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46234. offsetX *= -1;
  46235. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46236. var offsetY = evt.clientY - _this.previousPosition.y;
  46237. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46238. _this.previousPosition = {
  46239. x: evt.clientX,
  46240. y: evt.clientY
  46241. };
  46242. if (!noPreventDefault) {
  46243. evt.preventDefault();
  46244. }
  46245. }
  46246. };
  46247. }
  46248. this._onMouseMove = function (evt) {
  46249. if (!engine.isPointerLock) {
  46250. return;
  46251. }
  46252. if (engine.isInVRExclusivePointerMode) {
  46253. return;
  46254. }
  46255. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46256. if (_this.camera.getScene().useRightHandedSystem)
  46257. offsetX *= -1;
  46258. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46259. offsetX *= -1;
  46260. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46261. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46262. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46263. _this.previousPosition = null;
  46264. if (!noPreventDefault) {
  46265. evt.preventDefault();
  46266. }
  46267. };
  46268. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46269. element.addEventListener("mousemove", this._onMouseMove, false);
  46270. };
  46271. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46272. if (this._observer && element) {
  46273. this.camera.getScene().onPointerObservable.remove(this._observer);
  46274. if (this._onMouseMove) {
  46275. element.removeEventListener("mousemove", this._onMouseMove);
  46276. }
  46277. this._observer = null;
  46278. this._onMouseMove = null;
  46279. this.previousPosition = null;
  46280. }
  46281. };
  46282. FreeCameraMouseInput.prototype.getClassName = function () {
  46283. return "FreeCameraMouseInput";
  46284. };
  46285. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46286. return "mouse";
  46287. };
  46288. __decorate([
  46289. BABYLON.serialize()
  46290. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46291. __decorate([
  46292. BABYLON.serialize()
  46293. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46294. return FreeCameraMouseInput;
  46295. }());
  46296. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46297. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46298. })(BABYLON || (BABYLON = {}));
  46299. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46300. var BABYLON;
  46301. (function (BABYLON) {
  46302. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46303. function FreeCameraKeyboardMoveInput() {
  46304. this._keys = new Array();
  46305. this.keysUp = [38];
  46306. this.keysDown = [40];
  46307. this.keysLeft = [37];
  46308. this.keysRight = [39];
  46309. }
  46310. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46311. var _this = this;
  46312. if (this._onCanvasBlurObserver) {
  46313. return;
  46314. }
  46315. this._scene = this.camera.getScene();
  46316. this._engine = this._scene.getEngine();
  46317. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46318. _this._keys = [];
  46319. });
  46320. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46321. var evt = info.event;
  46322. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46323. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46324. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46325. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46326. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46327. var index = _this._keys.indexOf(evt.keyCode);
  46328. if (index === -1) {
  46329. _this._keys.push(evt.keyCode);
  46330. }
  46331. if (!noPreventDefault) {
  46332. evt.preventDefault();
  46333. }
  46334. }
  46335. }
  46336. else {
  46337. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46338. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46339. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46340. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46341. var index = _this._keys.indexOf(evt.keyCode);
  46342. if (index >= 0) {
  46343. _this._keys.splice(index, 1);
  46344. }
  46345. if (!noPreventDefault) {
  46346. evt.preventDefault();
  46347. }
  46348. }
  46349. }
  46350. });
  46351. };
  46352. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46353. if (this._scene) {
  46354. if (this._onKeyboardObserver) {
  46355. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46356. }
  46357. if (this._onCanvasBlurObserver) {
  46358. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46359. }
  46360. this._onKeyboardObserver = null;
  46361. this._onCanvasBlurObserver = null;
  46362. }
  46363. this._keys = [];
  46364. };
  46365. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46366. if (this._onKeyboardObserver) {
  46367. var camera = this.camera;
  46368. // Keyboard
  46369. for (var index = 0; index < this._keys.length; index++) {
  46370. var keyCode = this._keys[index];
  46371. var speed = camera._computeLocalCameraSpeed();
  46372. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46373. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46374. }
  46375. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46376. camera._localDirection.copyFromFloats(0, 0, speed);
  46377. }
  46378. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46379. camera._localDirection.copyFromFloats(speed, 0, 0);
  46380. }
  46381. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46382. camera._localDirection.copyFromFloats(0, 0, -speed);
  46383. }
  46384. if (camera.getScene().useRightHandedSystem) {
  46385. camera._localDirection.z *= -1;
  46386. }
  46387. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46388. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46389. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46390. }
  46391. }
  46392. };
  46393. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46394. return "FreeCameraKeyboardMoveInput";
  46395. };
  46396. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46397. this._keys = [];
  46398. };
  46399. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46400. return "keyboard";
  46401. };
  46402. __decorate([
  46403. BABYLON.serialize()
  46404. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46405. __decorate([
  46406. BABYLON.serialize()
  46407. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46408. __decorate([
  46409. BABYLON.serialize()
  46410. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46411. __decorate([
  46412. BABYLON.serialize()
  46413. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46414. return FreeCameraKeyboardMoveInput;
  46415. }());
  46416. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46417. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46418. })(BABYLON || (BABYLON = {}));
  46419. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46420. var BABYLON;
  46421. (function (BABYLON) {
  46422. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46423. __extends(FreeCameraInputsManager, _super);
  46424. function FreeCameraInputsManager(camera) {
  46425. return _super.call(this, camera) || this;
  46426. }
  46427. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46428. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46429. return this;
  46430. };
  46431. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46432. if (touchEnabled === void 0) { touchEnabled = true; }
  46433. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46434. return this;
  46435. };
  46436. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46437. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46438. return this;
  46439. };
  46440. FreeCameraInputsManager.prototype.addTouch = function () {
  46441. this.add(new BABYLON.FreeCameraTouchInput());
  46442. return this;
  46443. };
  46444. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46445. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46446. return this;
  46447. };
  46448. return FreeCameraInputsManager;
  46449. }(BABYLON.CameraInputsManager));
  46450. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46451. })(BABYLON || (BABYLON = {}));
  46452. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46453. var BABYLON;
  46454. (function (BABYLON) {
  46455. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46456. // Forcing to use the Universal camera
  46457. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46458. });
  46459. var FreeCamera = /** @class */ (function (_super) {
  46460. __extends(FreeCamera, _super);
  46461. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46462. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46463. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46464. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46465. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46466. _this.checkCollisions = false;
  46467. _this.applyGravity = false;
  46468. _this._needMoveForGravity = false;
  46469. _this._oldPosition = BABYLON.Vector3.Zero();
  46470. _this._diffPosition = BABYLON.Vector3.Zero();
  46471. _this._newPosition = BABYLON.Vector3.Zero();
  46472. // Collisions
  46473. _this._collisionMask = -1;
  46474. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46475. if (collidedMesh === void 0) { collidedMesh = null; }
  46476. //TODO move this to the collision coordinator!
  46477. if (_this.getScene().workerCollisions)
  46478. newPosition.multiplyInPlace(_this._collider._radius);
  46479. var updatePosition = function (newPos) {
  46480. _this._newPosition.copyFrom(newPos);
  46481. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46482. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46483. _this.position.addInPlace(_this._diffPosition);
  46484. if (_this.onCollide && collidedMesh) {
  46485. _this.onCollide(collidedMesh);
  46486. }
  46487. }
  46488. };
  46489. updatePosition(newPosition);
  46490. };
  46491. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46492. _this.inputs.addKeyboard().addMouse();
  46493. return _this;
  46494. }
  46495. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46496. //-- begin properties for backward compatibility for inputs
  46497. /**
  46498. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46499. * Higher values reduce sensitivity.
  46500. */
  46501. get: function () {
  46502. var mouse = this.inputs.attached["mouse"];
  46503. if (mouse)
  46504. return mouse.angularSensibility;
  46505. return 0;
  46506. },
  46507. /**
  46508. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46509. * Higher values reduce sensitivity.
  46510. */
  46511. set: function (value) {
  46512. var mouse = this.inputs.attached["mouse"];
  46513. if (mouse)
  46514. mouse.angularSensibility = value;
  46515. },
  46516. enumerable: true,
  46517. configurable: true
  46518. });
  46519. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46520. get: function () {
  46521. var keyboard = this.inputs.attached["keyboard"];
  46522. if (keyboard)
  46523. return keyboard.keysUp;
  46524. return [];
  46525. },
  46526. set: function (value) {
  46527. var keyboard = this.inputs.attached["keyboard"];
  46528. if (keyboard)
  46529. keyboard.keysUp = value;
  46530. },
  46531. enumerable: true,
  46532. configurable: true
  46533. });
  46534. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46535. get: function () {
  46536. var keyboard = this.inputs.attached["keyboard"];
  46537. if (keyboard)
  46538. return keyboard.keysDown;
  46539. return [];
  46540. },
  46541. set: function (value) {
  46542. var keyboard = this.inputs.attached["keyboard"];
  46543. if (keyboard)
  46544. keyboard.keysDown = value;
  46545. },
  46546. enumerable: true,
  46547. configurable: true
  46548. });
  46549. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46550. get: function () {
  46551. var keyboard = this.inputs.attached["keyboard"];
  46552. if (keyboard)
  46553. return keyboard.keysLeft;
  46554. return [];
  46555. },
  46556. set: function (value) {
  46557. var keyboard = this.inputs.attached["keyboard"];
  46558. if (keyboard)
  46559. keyboard.keysLeft = value;
  46560. },
  46561. enumerable: true,
  46562. configurable: true
  46563. });
  46564. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46565. get: function () {
  46566. var keyboard = this.inputs.attached["keyboard"];
  46567. if (keyboard)
  46568. return keyboard.keysRight;
  46569. return [];
  46570. },
  46571. set: function (value) {
  46572. var keyboard = this.inputs.attached["keyboard"];
  46573. if (keyboard)
  46574. keyboard.keysRight = value;
  46575. },
  46576. enumerable: true,
  46577. configurable: true
  46578. });
  46579. // Controls
  46580. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46581. this.inputs.attachElement(element, noPreventDefault);
  46582. };
  46583. FreeCamera.prototype.detachControl = function (element) {
  46584. this.inputs.detachElement(element);
  46585. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46586. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46587. };
  46588. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46589. get: function () {
  46590. return this._collisionMask;
  46591. },
  46592. set: function (mask) {
  46593. this._collisionMask = !isNaN(mask) ? mask : -1;
  46594. },
  46595. enumerable: true,
  46596. configurable: true
  46597. });
  46598. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46599. var globalPosition;
  46600. if (this.parent) {
  46601. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46602. }
  46603. else {
  46604. globalPosition = this.position;
  46605. }
  46606. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46607. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46608. if (!this._collider) {
  46609. this._collider = new BABYLON.Collider();
  46610. }
  46611. this._collider._radius = this.ellipsoid;
  46612. this._collider.collisionMask = this._collisionMask;
  46613. //no need for clone, as long as gravity is not on.
  46614. var actualDisplacement = displacement;
  46615. //add gravity to the direction to prevent the dual-collision checking
  46616. if (this.applyGravity) {
  46617. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46618. actualDisplacement = displacement.add(this.getScene().gravity);
  46619. }
  46620. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46621. };
  46622. FreeCamera.prototype._checkInputs = function () {
  46623. if (!this._localDirection) {
  46624. this._localDirection = BABYLON.Vector3.Zero();
  46625. this._transformedDirection = BABYLON.Vector3.Zero();
  46626. }
  46627. this.inputs.checkInputs();
  46628. _super.prototype._checkInputs.call(this);
  46629. };
  46630. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46631. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46632. };
  46633. FreeCamera.prototype._updatePosition = function () {
  46634. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46635. this._collideWithWorld(this.cameraDirection);
  46636. }
  46637. else {
  46638. _super.prototype._updatePosition.call(this);
  46639. }
  46640. };
  46641. FreeCamera.prototype.dispose = function () {
  46642. this.inputs.clear();
  46643. _super.prototype.dispose.call(this);
  46644. };
  46645. FreeCamera.prototype.getClassName = function () {
  46646. return "FreeCamera";
  46647. };
  46648. __decorate([
  46649. BABYLON.serializeAsVector3()
  46650. ], FreeCamera.prototype, "ellipsoid", void 0);
  46651. __decorate([
  46652. BABYLON.serializeAsVector3()
  46653. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46654. __decorate([
  46655. BABYLON.serialize()
  46656. ], FreeCamera.prototype, "checkCollisions", void 0);
  46657. __decorate([
  46658. BABYLON.serialize()
  46659. ], FreeCamera.prototype, "applyGravity", void 0);
  46660. return FreeCamera;
  46661. }(BABYLON.TargetCamera));
  46662. BABYLON.FreeCamera = FreeCamera;
  46663. })(BABYLON || (BABYLON = {}));
  46664. //# sourceMappingURL=babylon.freeCamera.js.map
  46665. var BABYLON;
  46666. (function (BABYLON) {
  46667. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46668. function ArcRotateCameraKeyboardMoveInput() {
  46669. this._keys = new Array();
  46670. this.keysUp = [38];
  46671. this.keysDown = [40];
  46672. this.keysLeft = [37];
  46673. this.keysRight = [39];
  46674. this.keysReset = [220];
  46675. this.panningSensibility = 50.0;
  46676. this.zoomingSensibility = 25.0;
  46677. this.useAltToZoom = true;
  46678. }
  46679. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46680. var _this = this;
  46681. if (this._onCanvasBlurObserver) {
  46682. return;
  46683. }
  46684. this._scene = this.camera.getScene();
  46685. this._engine = this._scene.getEngine();
  46686. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46687. _this._keys = [];
  46688. });
  46689. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46690. var evt = info.event;
  46691. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46692. _this._ctrlPressed = evt.ctrlKey;
  46693. _this._altPressed = evt.altKey;
  46694. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46695. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46696. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46697. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46698. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46699. var index = _this._keys.indexOf(evt.keyCode);
  46700. if (index === -1) {
  46701. _this._keys.push(evt.keyCode);
  46702. }
  46703. if (evt.preventDefault) {
  46704. if (!noPreventDefault) {
  46705. evt.preventDefault();
  46706. }
  46707. }
  46708. }
  46709. }
  46710. else {
  46711. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46712. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46713. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46714. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46715. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46716. var index = _this._keys.indexOf(evt.keyCode);
  46717. if (index >= 0) {
  46718. _this._keys.splice(index, 1);
  46719. }
  46720. if (evt.preventDefault) {
  46721. if (!noPreventDefault) {
  46722. evt.preventDefault();
  46723. }
  46724. }
  46725. }
  46726. }
  46727. });
  46728. };
  46729. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46730. if (this._scene) {
  46731. if (this._onKeyboardObserver) {
  46732. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46733. }
  46734. if (this._onCanvasBlurObserver) {
  46735. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46736. }
  46737. this._onKeyboardObserver = null;
  46738. this._onCanvasBlurObserver = null;
  46739. }
  46740. this._keys = [];
  46741. };
  46742. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46743. if (this._onKeyboardObserver) {
  46744. var camera = this.camera;
  46745. for (var index = 0; index < this._keys.length; index++) {
  46746. var keyCode = this._keys[index];
  46747. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46748. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46749. camera.inertialPanningX -= 1 / this.panningSensibility;
  46750. }
  46751. else {
  46752. camera.inertialAlphaOffset -= 0.01;
  46753. }
  46754. }
  46755. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46756. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46757. camera.inertialPanningY += 1 / this.panningSensibility;
  46758. }
  46759. else if (this._altPressed && this.useAltToZoom) {
  46760. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46761. }
  46762. else {
  46763. camera.inertialBetaOffset -= 0.01;
  46764. }
  46765. }
  46766. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46767. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46768. camera.inertialPanningX += 1 / this.panningSensibility;
  46769. }
  46770. else {
  46771. camera.inertialAlphaOffset += 0.01;
  46772. }
  46773. }
  46774. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46775. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46776. camera.inertialPanningY -= 1 / this.panningSensibility;
  46777. }
  46778. else if (this._altPressed && this.useAltToZoom) {
  46779. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46780. }
  46781. else {
  46782. camera.inertialBetaOffset += 0.01;
  46783. }
  46784. }
  46785. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46786. camera.restoreState();
  46787. }
  46788. }
  46789. }
  46790. };
  46791. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46792. return "ArcRotateCameraKeyboardMoveInput";
  46793. };
  46794. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46795. return "keyboard";
  46796. };
  46797. __decorate([
  46798. BABYLON.serialize()
  46799. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46800. __decorate([
  46801. BABYLON.serialize()
  46802. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46803. __decorate([
  46804. BABYLON.serialize()
  46805. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46806. __decorate([
  46807. BABYLON.serialize()
  46808. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46809. __decorate([
  46810. BABYLON.serialize()
  46811. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46812. __decorate([
  46813. BABYLON.serialize()
  46814. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46815. __decorate([
  46816. BABYLON.serialize()
  46817. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46818. __decorate([
  46819. BABYLON.serialize()
  46820. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46821. return ArcRotateCameraKeyboardMoveInput;
  46822. }());
  46823. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46824. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46825. })(BABYLON || (BABYLON = {}));
  46826. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46827. var BABYLON;
  46828. (function (BABYLON) {
  46829. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46830. function ArcRotateCameraMouseWheelInput() {
  46831. this.wheelPrecision = 3.0;
  46832. /**
  46833. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46834. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46835. */
  46836. this.wheelDeltaPercentage = 0;
  46837. }
  46838. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46839. var _this = this;
  46840. this._wheel = function (p, s) {
  46841. //sanity check - this should be a PointerWheel event.
  46842. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46843. return;
  46844. var event = p.event;
  46845. var delta = 0;
  46846. if (event.wheelDelta) {
  46847. if (_this.wheelDeltaPercentage) {
  46848. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46849. if (event.wheelDelta > 0) {
  46850. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46851. }
  46852. else {
  46853. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46854. }
  46855. }
  46856. else {
  46857. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46858. }
  46859. }
  46860. else if (event.detail) {
  46861. delta = -event.detail / _this.wheelPrecision;
  46862. }
  46863. if (delta)
  46864. _this.camera.inertialRadiusOffset += delta;
  46865. if (event.preventDefault) {
  46866. if (!noPreventDefault) {
  46867. event.preventDefault();
  46868. }
  46869. }
  46870. };
  46871. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46872. };
  46873. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46874. if (this._observer && element) {
  46875. this.camera.getScene().onPointerObservable.remove(this._observer);
  46876. this._observer = null;
  46877. this._wheel = null;
  46878. }
  46879. };
  46880. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46881. return "ArcRotateCameraMouseWheelInput";
  46882. };
  46883. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46884. return "mousewheel";
  46885. };
  46886. __decorate([
  46887. BABYLON.serialize()
  46888. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46889. __decorate([
  46890. BABYLON.serialize()
  46891. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46892. return ArcRotateCameraMouseWheelInput;
  46893. }());
  46894. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46895. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46896. })(BABYLON || (BABYLON = {}));
  46897. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46898. var BABYLON;
  46899. (function (BABYLON) {
  46900. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46901. function ArcRotateCameraPointersInput() {
  46902. this.buttons = [0, 1, 2];
  46903. this.angularSensibilityX = 1000.0;
  46904. this.angularSensibilityY = 1000.0;
  46905. this.pinchPrecision = 12.0;
  46906. /**
  46907. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46908. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46909. */
  46910. this.pinchDeltaPercentage = 0;
  46911. this.panningSensibility = 1000.0;
  46912. this.multiTouchPanning = true;
  46913. this.multiTouchPanAndZoom = true;
  46914. this._isPanClick = false;
  46915. this.pinchInwards = true;
  46916. }
  46917. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46918. var _this = this;
  46919. var engine = this.camera.getEngine();
  46920. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46921. var pointA = null;
  46922. var pointB = null;
  46923. var previousPinchSquaredDistance = 0;
  46924. var initialDistance = 0;
  46925. var twoFingerActivityCount = 0;
  46926. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46927. this._pointerInput = function (p, s) {
  46928. var evt = p.event;
  46929. var isTouch = p.event.pointerType === "touch";
  46930. if (engine.isInVRExclusivePointerMode) {
  46931. return;
  46932. }
  46933. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46934. return;
  46935. }
  46936. var srcElement = (evt.srcElement || evt.target);
  46937. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46938. try {
  46939. srcElement.setPointerCapture(evt.pointerId);
  46940. }
  46941. catch (e) {
  46942. //Nothing to do with the error. Execution will continue.
  46943. }
  46944. // Manage panning with pan button click
  46945. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46946. // manage pointers
  46947. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46948. if (pointA === null) {
  46949. pointA = cacheSoloPointer;
  46950. }
  46951. else if (pointB === null) {
  46952. pointB = cacheSoloPointer;
  46953. }
  46954. if (!noPreventDefault) {
  46955. evt.preventDefault();
  46956. element.focus();
  46957. }
  46958. }
  46959. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46960. _this.camera.restoreState();
  46961. }
  46962. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46963. try {
  46964. srcElement.releasePointerCapture(evt.pointerId);
  46965. }
  46966. catch (e) {
  46967. //Nothing to do with the error.
  46968. }
  46969. cacheSoloPointer = null;
  46970. previousPinchSquaredDistance = 0;
  46971. previousMultiTouchPanPosition.isPaning = false;
  46972. previousMultiTouchPanPosition.isPinching = false;
  46973. twoFingerActivityCount = 0;
  46974. initialDistance = 0;
  46975. if (!isTouch) {
  46976. pointB = null; // Mouse and pen are mono pointer
  46977. }
  46978. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46979. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46980. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46981. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46982. if (engine._badOS) {
  46983. pointA = pointB = null;
  46984. }
  46985. else {
  46986. //only remove the impacted pointer in case of multitouch allowing on most
  46987. //platforms switching from rotate to zoom and pan seamlessly.
  46988. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  46989. pointA = pointB;
  46990. pointB = null;
  46991. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46992. }
  46993. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  46994. pointB = null;
  46995. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46996. }
  46997. else {
  46998. pointA = pointB = null;
  46999. }
  47000. }
  47001. if (!noPreventDefault) {
  47002. evt.preventDefault();
  47003. }
  47004. }
  47005. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47006. if (!noPreventDefault) {
  47007. evt.preventDefault();
  47008. }
  47009. // One button down
  47010. if (pointA && pointB === null && cacheSoloPointer) {
  47011. if (_this.panningSensibility !== 0 &&
  47012. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47013. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47014. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47015. }
  47016. else {
  47017. var offsetX = evt.clientX - cacheSoloPointer.x;
  47018. var offsetY = evt.clientY - cacheSoloPointer.y;
  47019. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47020. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47021. }
  47022. cacheSoloPointer.x = evt.clientX;
  47023. cacheSoloPointer.y = evt.clientY;
  47024. }
  47025. // Two buttons down: pinch/pan
  47026. else if (pointA && pointB) {
  47027. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47028. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47029. ed.x = evt.clientX;
  47030. ed.y = evt.clientY;
  47031. var direction = _this.pinchInwards ? 1 : -1;
  47032. var distX = pointA.x - pointB.x;
  47033. var distY = pointA.y - pointB.y;
  47034. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47035. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47036. if (previousPinchSquaredDistance === 0) {
  47037. initialDistance = pinchDistance;
  47038. previousPinchSquaredDistance = pinchSquaredDistance;
  47039. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47040. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47041. return;
  47042. }
  47043. if (_this.multiTouchPanAndZoom) {
  47044. if (_this.pinchDeltaPercentage) {
  47045. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47046. }
  47047. else {
  47048. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47049. (_this.pinchPrecision *
  47050. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47051. direction);
  47052. }
  47053. if (_this.panningSensibility !== 0) {
  47054. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47055. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47056. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47057. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47058. previousMultiTouchPanPosition.x = pointersCenterX;
  47059. previousMultiTouchPanPosition.y = pointersCenterY;
  47060. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47061. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47062. }
  47063. }
  47064. else {
  47065. twoFingerActivityCount++;
  47066. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47067. if (_this.pinchDeltaPercentage) {
  47068. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47069. }
  47070. else {
  47071. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47072. (_this.pinchPrecision *
  47073. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47074. direction);
  47075. }
  47076. previousMultiTouchPanPosition.isPaning = false;
  47077. previousMultiTouchPanPosition.isPinching = true;
  47078. }
  47079. else {
  47080. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47081. if (!previousMultiTouchPanPosition.isPaning) {
  47082. previousMultiTouchPanPosition.isPaning = true;
  47083. previousMultiTouchPanPosition.isPinching = false;
  47084. previousMultiTouchPanPosition.x = ed.x;
  47085. previousMultiTouchPanPosition.y = ed.y;
  47086. return;
  47087. }
  47088. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47089. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47090. }
  47091. }
  47092. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47093. previousMultiTouchPanPosition.x = ed.x;
  47094. previousMultiTouchPanPosition.y = ed.y;
  47095. }
  47096. }
  47097. previousPinchSquaredDistance = pinchSquaredDistance;
  47098. }
  47099. }
  47100. };
  47101. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47102. this._onContextMenu = function (evt) {
  47103. evt.preventDefault();
  47104. };
  47105. if (!this.camera._useCtrlForPanning) {
  47106. element.addEventListener("contextmenu", this._onContextMenu, false);
  47107. }
  47108. this._onLostFocus = function () {
  47109. //this._keys = [];
  47110. pointA = pointB = null;
  47111. previousPinchSquaredDistance = 0;
  47112. previousMultiTouchPanPosition.isPaning = false;
  47113. previousMultiTouchPanPosition.isPinching = false;
  47114. twoFingerActivityCount = 0;
  47115. cacheSoloPointer = null;
  47116. initialDistance = 0;
  47117. };
  47118. this._onMouseMove = function (evt) {
  47119. if (!engine.isPointerLock) {
  47120. return;
  47121. }
  47122. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47123. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47124. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47125. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47126. if (!noPreventDefault) {
  47127. evt.preventDefault();
  47128. }
  47129. };
  47130. this._onGestureStart = function (e) {
  47131. if (window.MSGesture === undefined) {
  47132. return;
  47133. }
  47134. if (!_this._MSGestureHandler) {
  47135. _this._MSGestureHandler = new MSGesture();
  47136. _this._MSGestureHandler.target = element;
  47137. }
  47138. _this._MSGestureHandler.addPointer(e.pointerId);
  47139. };
  47140. this._onGesture = function (e) {
  47141. _this.camera.radius *= e.scale;
  47142. if (e.preventDefault) {
  47143. if (!noPreventDefault) {
  47144. e.stopPropagation();
  47145. e.preventDefault();
  47146. }
  47147. }
  47148. };
  47149. element.addEventListener("mousemove", this._onMouseMove, false);
  47150. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47151. element.addEventListener("MSGestureChange", this._onGesture, false);
  47152. BABYLON.Tools.RegisterTopRootEvents([
  47153. { name: "blur", handler: this._onLostFocus }
  47154. ]);
  47155. };
  47156. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47157. if (this._onLostFocus) {
  47158. BABYLON.Tools.UnregisterTopRootEvents([
  47159. { name: "blur", handler: this._onLostFocus }
  47160. ]);
  47161. }
  47162. if (element && this._observer) {
  47163. this.camera.getScene().onPointerObservable.remove(this._observer);
  47164. this._observer = null;
  47165. if (this._onContextMenu) {
  47166. element.removeEventListener("contextmenu", this._onContextMenu);
  47167. }
  47168. if (this._onMouseMove) {
  47169. element.removeEventListener("mousemove", this._onMouseMove);
  47170. }
  47171. if (this._onGestureStart) {
  47172. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47173. }
  47174. if (this._onGesture) {
  47175. element.removeEventListener("MSGestureChange", this._onGesture);
  47176. }
  47177. this._isPanClick = false;
  47178. this.pinchInwards = true;
  47179. this._onMouseMove = null;
  47180. this._onGestureStart = null;
  47181. this._onGesture = null;
  47182. this._MSGestureHandler = null;
  47183. this._onLostFocus = null;
  47184. this._onContextMenu = null;
  47185. }
  47186. };
  47187. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47188. return "ArcRotateCameraPointersInput";
  47189. };
  47190. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47191. return "pointers";
  47192. };
  47193. __decorate([
  47194. BABYLON.serialize()
  47195. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47196. __decorate([
  47197. BABYLON.serialize()
  47198. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47199. __decorate([
  47200. BABYLON.serialize()
  47201. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47202. __decorate([
  47203. BABYLON.serialize()
  47204. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47205. __decorate([
  47206. BABYLON.serialize()
  47207. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47208. __decorate([
  47209. BABYLON.serialize()
  47210. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47211. __decorate([
  47212. BABYLON.serialize()
  47213. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47214. __decorate([
  47215. BABYLON.serialize()
  47216. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47217. return ArcRotateCameraPointersInput;
  47218. }());
  47219. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47220. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47221. })(BABYLON || (BABYLON = {}));
  47222. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47223. var BABYLON;
  47224. (function (BABYLON) {
  47225. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47226. __extends(ArcRotateCameraInputsManager, _super);
  47227. function ArcRotateCameraInputsManager(camera) {
  47228. return _super.call(this, camera) || this;
  47229. }
  47230. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47231. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47232. return this;
  47233. };
  47234. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47235. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47236. return this;
  47237. };
  47238. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47239. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47240. return this;
  47241. };
  47242. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47243. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47244. return this;
  47245. };
  47246. return ArcRotateCameraInputsManager;
  47247. }(BABYLON.CameraInputsManager));
  47248. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47249. })(BABYLON || (BABYLON = {}));
  47250. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47251. var BABYLON;
  47252. (function (BABYLON) {
  47253. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47254. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47255. });
  47256. var ArcRotateCamera = /** @class */ (function (_super) {
  47257. __extends(ArcRotateCamera, _super);
  47258. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47259. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47260. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47261. _this.inertialAlphaOffset = 0;
  47262. _this.inertialBetaOffset = 0;
  47263. _this.inertialRadiusOffset = 0;
  47264. _this.lowerAlphaLimit = null;
  47265. _this.upperAlphaLimit = null;
  47266. _this.lowerBetaLimit = 0.01;
  47267. _this.upperBetaLimit = Math.PI;
  47268. _this.lowerRadiusLimit = null;
  47269. _this.upperRadiusLimit = null;
  47270. _this.inertialPanningX = 0;
  47271. _this.inertialPanningY = 0;
  47272. _this.pinchToPanMaxDistance = 20;
  47273. _this.panningDistanceLimit = null;
  47274. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47275. _this.panningInertia = 0.9;
  47276. //-- end properties for backward compatibility for inputs
  47277. _this.zoomOnFactor = 1;
  47278. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47279. _this.allowUpsideDown = true;
  47280. _this._viewMatrix = new BABYLON.Matrix();
  47281. // Panning
  47282. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47283. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47284. _this.checkCollisions = false;
  47285. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47286. _this._previousPosition = BABYLON.Vector3.Zero();
  47287. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47288. _this._newPosition = BABYLON.Vector3.Zero();
  47289. _this._computationVector = BABYLON.Vector3.Zero();
  47290. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47291. if (collidedMesh === void 0) { collidedMesh = null; }
  47292. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47293. newPosition.multiplyInPlace(_this._collider._radius);
  47294. }
  47295. if (!collidedMesh) {
  47296. _this._previousPosition.copyFrom(_this.position);
  47297. }
  47298. else {
  47299. _this.setPosition(newPosition);
  47300. if (_this.onCollide) {
  47301. _this.onCollide(collidedMesh);
  47302. }
  47303. }
  47304. // Recompute because of constraints
  47305. var cosa = Math.cos(_this.alpha);
  47306. var sina = Math.sin(_this.alpha);
  47307. var cosb = Math.cos(_this.beta);
  47308. var sinb = Math.sin(_this.beta);
  47309. if (sinb === 0) {
  47310. sinb = 0.0001;
  47311. }
  47312. var target = _this._getTargetPosition();
  47313. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47314. target.addToRef(_this._computationVector, _this._newPosition);
  47315. _this.position.copyFrom(_this._newPosition);
  47316. var up = _this.upVector;
  47317. if (_this.allowUpsideDown && _this.beta < 0) {
  47318. up = up.clone();
  47319. up = up.negate();
  47320. }
  47321. _this._computeViewMatrix(_this.position, target, up);
  47322. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47323. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47324. _this._collisionTriggered = false;
  47325. };
  47326. _this._target = BABYLON.Vector3.Zero();
  47327. if (target) {
  47328. _this.setTarget(target);
  47329. }
  47330. _this.alpha = alpha;
  47331. _this.beta = beta;
  47332. _this.radius = radius;
  47333. _this.getViewMatrix();
  47334. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47335. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47336. return _this;
  47337. }
  47338. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47339. get: function () {
  47340. return this._target;
  47341. },
  47342. set: function (value) {
  47343. this.setTarget(value);
  47344. },
  47345. enumerable: true,
  47346. configurable: true
  47347. });
  47348. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47349. //-- begin properties for backward compatibility for inputs
  47350. get: function () {
  47351. var pointers = this.inputs.attached["pointers"];
  47352. if (pointers)
  47353. return pointers.angularSensibilityX;
  47354. return 0;
  47355. },
  47356. set: function (value) {
  47357. var pointers = this.inputs.attached["pointers"];
  47358. if (pointers) {
  47359. pointers.angularSensibilityX = value;
  47360. }
  47361. },
  47362. enumerable: true,
  47363. configurable: true
  47364. });
  47365. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47366. get: function () {
  47367. var pointers = this.inputs.attached["pointers"];
  47368. if (pointers)
  47369. return pointers.angularSensibilityY;
  47370. return 0;
  47371. },
  47372. set: function (value) {
  47373. var pointers = this.inputs.attached["pointers"];
  47374. if (pointers) {
  47375. pointers.angularSensibilityY = value;
  47376. }
  47377. },
  47378. enumerable: true,
  47379. configurable: true
  47380. });
  47381. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47382. get: function () {
  47383. var pointers = this.inputs.attached["pointers"];
  47384. if (pointers)
  47385. return pointers.pinchPrecision;
  47386. return 0;
  47387. },
  47388. set: function (value) {
  47389. var pointers = this.inputs.attached["pointers"];
  47390. if (pointers) {
  47391. pointers.pinchPrecision = value;
  47392. }
  47393. },
  47394. enumerable: true,
  47395. configurable: true
  47396. });
  47397. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47398. get: function () {
  47399. var pointers = this.inputs.attached["pointers"];
  47400. if (pointers)
  47401. return pointers.pinchDeltaPercentage;
  47402. return 0;
  47403. },
  47404. set: function (value) {
  47405. var pointers = this.inputs.attached["pointers"];
  47406. if (pointers) {
  47407. pointers.pinchDeltaPercentage = value;
  47408. }
  47409. },
  47410. enumerable: true,
  47411. configurable: true
  47412. });
  47413. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47414. get: function () {
  47415. var pointers = this.inputs.attached["pointers"];
  47416. if (pointers)
  47417. return pointers.panningSensibility;
  47418. return 0;
  47419. },
  47420. set: function (value) {
  47421. var pointers = this.inputs.attached["pointers"];
  47422. if (pointers) {
  47423. pointers.panningSensibility = value;
  47424. }
  47425. },
  47426. enumerable: true,
  47427. configurable: true
  47428. });
  47429. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47430. get: function () {
  47431. var keyboard = this.inputs.attached["keyboard"];
  47432. if (keyboard)
  47433. return keyboard.keysUp;
  47434. return [];
  47435. },
  47436. set: function (value) {
  47437. var keyboard = this.inputs.attached["keyboard"];
  47438. if (keyboard)
  47439. keyboard.keysUp = value;
  47440. },
  47441. enumerable: true,
  47442. configurable: true
  47443. });
  47444. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47445. get: function () {
  47446. var keyboard = this.inputs.attached["keyboard"];
  47447. if (keyboard)
  47448. return keyboard.keysDown;
  47449. return [];
  47450. },
  47451. set: function (value) {
  47452. var keyboard = this.inputs.attached["keyboard"];
  47453. if (keyboard)
  47454. keyboard.keysDown = value;
  47455. },
  47456. enumerable: true,
  47457. configurable: true
  47458. });
  47459. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47460. get: function () {
  47461. var keyboard = this.inputs.attached["keyboard"];
  47462. if (keyboard)
  47463. return keyboard.keysLeft;
  47464. return [];
  47465. },
  47466. set: function (value) {
  47467. var keyboard = this.inputs.attached["keyboard"];
  47468. if (keyboard)
  47469. keyboard.keysLeft = value;
  47470. },
  47471. enumerable: true,
  47472. configurable: true
  47473. });
  47474. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47475. get: function () {
  47476. var keyboard = this.inputs.attached["keyboard"];
  47477. if (keyboard)
  47478. return keyboard.keysRight;
  47479. return [];
  47480. },
  47481. set: function (value) {
  47482. var keyboard = this.inputs.attached["keyboard"];
  47483. if (keyboard)
  47484. keyboard.keysRight = value;
  47485. },
  47486. enumerable: true,
  47487. configurable: true
  47488. });
  47489. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47490. get: function () {
  47491. var mousewheel = this.inputs.attached["mousewheel"];
  47492. if (mousewheel)
  47493. return mousewheel.wheelPrecision;
  47494. return 0;
  47495. },
  47496. set: function (value) {
  47497. var mousewheel = this.inputs.attached["mousewheel"];
  47498. if (mousewheel)
  47499. mousewheel.wheelPrecision = value;
  47500. },
  47501. enumerable: true,
  47502. configurable: true
  47503. });
  47504. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47505. get: function () {
  47506. var mousewheel = this.inputs.attached["mousewheel"];
  47507. if (mousewheel)
  47508. return mousewheel.wheelDeltaPercentage;
  47509. return 0;
  47510. },
  47511. set: function (value) {
  47512. var mousewheel = this.inputs.attached["mousewheel"];
  47513. if (mousewheel)
  47514. mousewheel.wheelDeltaPercentage = value;
  47515. },
  47516. enumerable: true,
  47517. configurable: true
  47518. });
  47519. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47520. get: function () {
  47521. return this._bouncingBehavior;
  47522. },
  47523. enumerable: true,
  47524. configurable: true
  47525. });
  47526. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47527. get: function () {
  47528. return this._bouncingBehavior != null;
  47529. },
  47530. set: function (value) {
  47531. if (value === this.useBouncingBehavior) {
  47532. return;
  47533. }
  47534. if (value) {
  47535. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47536. this.addBehavior(this._bouncingBehavior);
  47537. }
  47538. else if (this._bouncingBehavior) {
  47539. this.removeBehavior(this._bouncingBehavior);
  47540. this._bouncingBehavior = null;
  47541. }
  47542. },
  47543. enumerable: true,
  47544. configurable: true
  47545. });
  47546. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47547. get: function () {
  47548. return this._framingBehavior;
  47549. },
  47550. enumerable: true,
  47551. configurable: true
  47552. });
  47553. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47554. get: function () {
  47555. return this._framingBehavior != null;
  47556. },
  47557. set: function (value) {
  47558. if (value === this.useFramingBehavior) {
  47559. return;
  47560. }
  47561. if (value) {
  47562. this._framingBehavior = new BABYLON.FramingBehavior();
  47563. this.addBehavior(this._framingBehavior);
  47564. }
  47565. else if (this._framingBehavior) {
  47566. this.removeBehavior(this._framingBehavior);
  47567. this._framingBehavior = null;
  47568. }
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47574. get: function () {
  47575. return this._autoRotationBehavior;
  47576. },
  47577. enumerable: true,
  47578. configurable: true
  47579. });
  47580. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47581. get: function () {
  47582. return this._autoRotationBehavior != null;
  47583. },
  47584. set: function (value) {
  47585. if (value === this.useAutoRotationBehavior) {
  47586. return;
  47587. }
  47588. if (value) {
  47589. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47590. this.addBehavior(this._autoRotationBehavior);
  47591. }
  47592. else if (this._autoRotationBehavior) {
  47593. this.removeBehavior(this._autoRotationBehavior);
  47594. this._autoRotationBehavior = null;
  47595. }
  47596. },
  47597. enumerable: true,
  47598. configurable: true
  47599. });
  47600. // Cache
  47601. ArcRotateCamera.prototype._initCache = function () {
  47602. _super.prototype._initCache.call(this);
  47603. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47604. this._cache.alpha = undefined;
  47605. this._cache.beta = undefined;
  47606. this._cache.radius = undefined;
  47607. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47608. };
  47609. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47610. if (!ignoreParentClass) {
  47611. _super.prototype._updateCache.call(this);
  47612. }
  47613. this._cache._target.copyFrom(this._getTargetPosition());
  47614. this._cache.alpha = this.alpha;
  47615. this._cache.beta = this.beta;
  47616. this._cache.radius = this.radius;
  47617. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47618. };
  47619. ArcRotateCamera.prototype._getTargetPosition = function () {
  47620. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47621. var pos = this._targetHost.getAbsolutePosition();
  47622. if (this._targetBoundingCenter) {
  47623. pos.addToRef(this._targetBoundingCenter, this._target);
  47624. }
  47625. else {
  47626. this._target.copyFrom(pos);
  47627. }
  47628. }
  47629. var lockedTargetPosition = this._getLockedTargetPosition();
  47630. if (lockedTargetPosition) {
  47631. return lockedTargetPosition;
  47632. }
  47633. return this._target;
  47634. };
  47635. ArcRotateCamera.prototype.storeState = function () {
  47636. this._storedAlpha = this.alpha;
  47637. this._storedBeta = this.beta;
  47638. this._storedRadius = this.radius;
  47639. this._storedTarget = this._getTargetPosition().clone();
  47640. return _super.prototype.storeState.call(this);
  47641. };
  47642. /**
  47643. * Restored camera state. You must call storeState() first
  47644. */
  47645. ArcRotateCamera.prototype._restoreStateValues = function () {
  47646. if (!_super.prototype._restoreStateValues.call(this)) {
  47647. return false;
  47648. }
  47649. this.alpha = this._storedAlpha;
  47650. this.beta = this._storedBeta;
  47651. this.radius = this._storedRadius;
  47652. this.setTarget(this._storedTarget.clone());
  47653. this.inertialAlphaOffset = 0;
  47654. this.inertialBetaOffset = 0;
  47655. this.inertialRadiusOffset = 0;
  47656. this.inertialPanningX = 0;
  47657. this.inertialPanningY = 0;
  47658. return true;
  47659. };
  47660. // Synchronized
  47661. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47662. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47663. return false;
  47664. return this._cache._target.equals(this._getTargetPosition())
  47665. && this._cache.alpha === this.alpha
  47666. && this._cache.beta === this.beta
  47667. && this._cache.radius === this.radius
  47668. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47669. };
  47670. // Methods
  47671. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47672. var _this = this;
  47673. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47674. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47675. this._useCtrlForPanning = useCtrlForPanning;
  47676. this._panningMouseButton = panningMouseButton;
  47677. this.inputs.attachElement(element, noPreventDefault);
  47678. this._reset = function () {
  47679. _this.inertialAlphaOffset = 0;
  47680. _this.inertialBetaOffset = 0;
  47681. _this.inertialRadiusOffset = 0;
  47682. _this.inertialPanningX = 0;
  47683. _this.inertialPanningY = 0;
  47684. };
  47685. };
  47686. ArcRotateCamera.prototype.detachControl = function (element) {
  47687. this.inputs.detachElement(element);
  47688. if (this._reset) {
  47689. this._reset();
  47690. }
  47691. };
  47692. ArcRotateCamera.prototype._checkInputs = function () {
  47693. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47694. if (this._collisionTriggered) {
  47695. return;
  47696. }
  47697. this.inputs.checkInputs();
  47698. // Inertia
  47699. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47700. var inertialAlphaOffset = this.inertialAlphaOffset;
  47701. if (this.beta <= 0)
  47702. inertialAlphaOffset *= -1;
  47703. if (this.getScene().useRightHandedSystem)
  47704. inertialAlphaOffset *= -1;
  47705. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47706. inertialAlphaOffset *= -1;
  47707. this.alpha += inertialAlphaOffset;
  47708. this.beta += this.inertialBetaOffset;
  47709. this.radius -= this.inertialRadiusOffset;
  47710. this.inertialAlphaOffset *= this.inertia;
  47711. this.inertialBetaOffset *= this.inertia;
  47712. this.inertialRadiusOffset *= this.inertia;
  47713. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47714. this.inertialAlphaOffset = 0;
  47715. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47716. this.inertialBetaOffset = 0;
  47717. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47718. this.inertialRadiusOffset = 0;
  47719. }
  47720. // Panning inertia
  47721. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47722. if (!this._localDirection) {
  47723. this._localDirection = BABYLON.Vector3.Zero();
  47724. this._transformedDirection = BABYLON.Vector3.Zero();
  47725. }
  47726. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47727. this._localDirection.multiplyInPlace(this.panningAxis);
  47728. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47729. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47730. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47731. if (!this.panningAxis.y) {
  47732. this._transformedDirection.y = 0;
  47733. }
  47734. if (!this._targetHost) {
  47735. if (this.panningDistanceLimit) {
  47736. this._transformedDirection.addInPlace(this._target);
  47737. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47738. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47739. this._target.copyFrom(this._transformedDirection);
  47740. }
  47741. }
  47742. else {
  47743. this._target.addInPlace(this._transformedDirection);
  47744. }
  47745. }
  47746. this.inertialPanningX *= this.panningInertia;
  47747. this.inertialPanningY *= this.panningInertia;
  47748. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47749. this.inertialPanningX = 0;
  47750. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47751. this.inertialPanningY = 0;
  47752. }
  47753. // Limits
  47754. this._checkLimits();
  47755. _super.prototype._checkInputs.call(this);
  47756. };
  47757. ArcRotateCamera.prototype._checkLimits = function () {
  47758. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47759. if (this.allowUpsideDown && this.beta > Math.PI) {
  47760. this.beta = this.beta - (2 * Math.PI);
  47761. }
  47762. }
  47763. else {
  47764. if (this.beta < this.lowerBetaLimit) {
  47765. this.beta = this.lowerBetaLimit;
  47766. }
  47767. }
  47768. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47769. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47770. this.beta = this.beta + (2 * Math.PI);
  47771. }
  47772. }
  47773. else {
  47774. if (this.beta > this.upperBetaLimit) {
  47775. this.beta = this.upperBetaLimit;
  47776. }
  47777. }
  47778. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47779. this.alpha = this.lowerAlphaLimit;
  47780. }
  47781. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47782. this.alpha = this.upperAlphaLimit;
  47783. }
  47784. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47785. this.radius = this.lowerRadiusLimit;
  47786. }
  47787. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47788. this.radius = this.upperRadiusLimit;
  47789. }
  47790. };
  47791. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47792. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47793. this.radius = this._computationVector.length();
  47794. if (this.radius === 0) {
  47795. this.radius = 0.0001; // Just to avoid division by zero
  47796. }
  47797. // Alpha
  47798. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47799. if (this._computationVector.z < 0) {
  47800. this.alpha = 2 * Math.PI - this.alpha;
  47801. }
  47802. // Beta
  47803. this.beta = Math.acos(this._computationVector.y / this.radius);
  47804. this._checkLimits();
  47805. };
  47806. ArcRotateCamera.prototype.setPosition = function (position) {
  47807. if (this.position.equals(position)) {
  47808. return;
  47809. }
  47810. this.position.copyFrom(position);
  47811. this.rebuildAnglesAndRadius();
  47812. };
  47813. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47814. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47815. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47816. if (target.getBoundingInfo) {
  47817. if (toBoundingCenter) {
  47818. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47819. }
  47820. else {
  47821. this._targetBoundingCenter = null;
  47822. }
  47823. this._targetHost = target;
  47824. this._target = this._getTargetPosition();
  47825. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47826. }
  47827. else {
  47828. var newTarget = target;
  47829. var currentTarget = this._getTargetPosition();
  47830. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47831. return;
  47832. }
  47833. this._targetHost = null;
  47834. this._target = newTarget;
  47835. this._targetBoundingCenter = null;
  47836. this.onMeshTargetChangedObservable.notifyObservers(null);
  47837. }
  47838. this.rebuildAnglesAndRadius();
  47839. };
  47840. ArcRotateCamera.prototype._getViewMatrix = function () {
  47841. // Compute
  47842. var cosa = Math.cos(this.alpha);
  47843. var sina = Math.sin(this.alpha);
  47844. var cosb = Math.cos(this.beta);
  47845. var sinb = Math.sin(this.beta);
  47846. if (sinb === 0) {
  47847. sinb = 0.0001;
  47848. }
  47849. var target = this._getTargetPosition();
  47850. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47851. target.addToRef(this._computationVector, this._newPosition);
  47852. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47853. if (!this._collider) {
  47854. this._collider = new BABYLON.Collider();
  47855. }
  47856. this._collider._radius = this.collisionRadius;
  47857. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47858. this._collisionTriggered = true;
  47859. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47860. }
  47861. else {
  47862. this.position.copyFrom(this._newPosition);
  47863. var up = this.upVector;
  47864. if (this.allowUpsideDown && sinb < 0) {
  47865. up = up.clone();
  47866. up = up.negate();
  47867. }
  47868. this._computeViewMatrix(this.position, target, up);
  47869. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47870. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47871. }
  47872. this._currentTarget = target;
  47873. return this._viewMatrix;
  47874. };
  47875. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47876. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47877. meshes = meshes || this.getScene().meshes;
  47878. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47879. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47880. this.radius = distance * this.zoomOnFactor;
  47881. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47882. };
  47883. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47884. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47885. var meshesOrMinMaxVector;
  47886. var distance;
  47887. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47888. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47889. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47890. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47891. }
  47892. else { //minMaxVector and distance
  47893. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47894. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47895. distance = minMaxVectorAndDistance.distance;
  47896. }
  47897. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47898. if (!doNotUpdateMaxZ) {
  47899. this.maxZ = distance * 2;
  47900. }
  47901. };
  47902. /**
  47903. * @override
  47904. * Override Camera.createRigCamera
  47905. */
  47906. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47907. var alphaShift = 0;
  47908. switch (this.cameraRigMode) {
  47909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47911. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47912. case BABYLON.Camera.RIG_MODE_VR:
  47913. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47914. break;
  47915. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47916. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47917. break;
  47918. }
  47919. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47920. rigCam._cameraRigParams = {};
  47921. return rigCam;
  47922. };
  47923. /**
  47924. * @override
  47925. * Override Camera._updateRigCameras
  47926. */
  47927. ArcRotateCamera.prototype._updateRigCameras = function () {
  47928. var camLeft = this._rigCameras[0];
  47929. var camRight = this._rigCameras[1];
  47930. camLeft.beta = camRight.beta = this.beta;
  47931. camLeft.radius = camRight.radius = this.radius;
  47932. switch (this.cameraRigMode) {
  47933. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47934. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47935. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47936. case BABYLON.Camera.RIG_MODE_VR:
  47937. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47938. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47939. break;
  47940. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47941. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47942. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47943. break;
  47944. }
  47945. _super.prototype._updateRigCameras.call(this);
  47946. };
  47947. ArcRotateCamera.prototype.dispose = function () {
  47948. this.inputs.clear();
  47949. _super.prototype.dispose.call(this);
  47950. };
  47951. ArcRotateCamera.prototype.getClassName = function () {
  47952. return "ArcRotateCamera";
  47953. };
  47954. __decorate([
  47955. BABYLON.serialize()
  47956. ], ArcRotateCamera.prototype, "alpha", void 0);
  47957. __decorate([
  47958. BABYLON.serialize()
  47959. ], ArcRotateCamera.prototype, "beta", void 0);
  47960. __decorate([
  47961. BABYLON.serialize()
  47962. ], ArcRotateCamera.prototype, "radius", void 0);
  47963. __decorate([
  47964. BABYLON.serializeAsVector3("target")
  47965. ], ArcRotateCamera.prototype, "_target", void 0);
  47966. __decorate([
  47967. BABYLON.serialize()
  47968. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47969. __decorate([
  47970. BABYLON.serialize()
  47971. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47972. __decorate([
  47973. BABYLON.serialize()
  47974. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47975. __decorate([
  47976. BABYLON.serialize()
  47977. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47978. __decorate([
  47979. BABYLON.serialize()
  47980. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47981. __decorate([
  47982. BABYLON.serialize()
  47983. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47984. __decorate([
  47985. BABYLON.serialize()
  47986. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  47987. __decorate([
  47988. BABYLON.serialize()
  47989. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  47990. __decorate([
  47991. BABYLON.serialize()
  47992. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  47993. __decorate([
  47994. BABYLON.serialize()
  47995. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  47996. __decorate([
  47997. BABYLON.serialize()
  47998. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  47999. __decorate([
  48000. BABYLON.serialize()
  48001. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48002. __decorate([
  48003. BABYLON.serialize()
  48004. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48005. __decorate([
  48006. BABYLON.serializeAsVector3()
  48007. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48008. __decorate([
  48009. BABYLON.serialize()
  48010. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48011. __decorate([
  48012. BABYLON.serialize()
  48013. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48014. __decorate([
  48015. BABYLON.serialize()
  48016. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48017. return ArcRotateCamera;
  48018. }(BABYLON.TargetCamera));
  48019. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48020. })(BABYLON || (BABYLON = {}));
  48021. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48022. var BABYLON;
  48023. (function (BABYLON) {
  48024. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48025. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48026. });
  48027. /**
  48028. * The HemisphericLight simulates the ambient environment light,
  48029. * so the passed direction is the light reflection direction, not the incoming direction.
  48030. */
  48031. var HemisphericLight = /** @class */ (function (_super) {
  48032. __extends(HemisphericLight, _super);
  48033. /**
  48034. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48035. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48036. * The HemisphericLight can't cast shadows.
  48037. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48038. * @param name The friendly name of the light
  48039. * @param direction The direction of the light reflection
  48040. * @param scene The scene the light belongs to
  48041. */
  48042. function HemisphericLight(name, direction, scene) {
  48043. var _this = _super.call(this, name, scene) || this;
  48044. /**
  48045. * The groundColor is the light in the opposite direction to the one specified during creation.
  48046. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  48047. */
  48048. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48049. _this.direction = direction || BABYLON.Vector3.Up();
  48050. return _this;
  48051. }
  48052. HemisphericLight.prototype._buildUniformLayout = function () {
  48053. this._uniformBuffer.addUniform("vLightData", 4);
  48054. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48055. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48056. this._uniformBuffer.addUniform("vLightGround", 3);
  48057. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48058. this._uniformBuffer.addUniform("depthValues", 2);
  48059. this._uniformBuffer.create();
  48060. };
  48061. /**
  48062. * Returns the string "HemisphericLight".
  48063. * @return The class name
  48064. */
  48065. HemisphericLight.prototype.getClassName = function () {
  48066. return "HemisphericLight";
  48067. };
  48068. /**
  48069. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48070. * Returns the updated direction.
  48071. * @param target The target the direction should point to
  48072. * @return The computed direction
  48073. */
  48074. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48075. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48076. return this.direction;
  48077. };
  48078. /**
  48079. * Returns the shadow generator associated to the light.
  48080. * @returns Always null for hemispheric lights because it does not support shadows.
  48081. */
  48082. HemisphericLight.prototype.getShadowGenerator = function () {
  48083. return null;
  48084. };
  48085. /**
  48086. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48087. * @param effect The effect to update
  48088. * @param lightIndex The index of the light in the effect to update
  48089. * @returns The hemispheric light
  48090. */
  48091. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48092. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48093. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48094. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48095. return this;
  48096. };
  48097. /**
  48098. * @hidden internal use only.
  48099. */
  48100. HemisphericLight.prototype._getWorldMatrix = function () {
  48101. if (!this._worldMatrix) {
  48102. this._worldMatrix = BABYLON.Matrix.Identity();
  48103. }
  48104. return this._worldMatrix;
  48105. };
  48106. /**
  48107. * Returns the integer 3.
  48108. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48109. */
  48110. HemisphericLight.prototype.getTypeID = function () {
  48111. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48112. };
  48113. /**
  48114. * Prepares the list of defines specific to the light type.
  48115. * @param defines the list of defines
  48116. * @param lightIndex defines the index of the light for the effect
  48117. */
  48118. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48119. defines["HEMILIGHT" + lightIndex] = true;
  48120. };
  48121. __decorate([
  48122. BABYLON.serializeAsColor3()
  48123. ], HemisphericLight.prototype, "groundColor", void 0);
  48124. __decorate([
  48125. BABYLON.serializeAsVector3()
  48126. ], HemisphericLight.prototype, "direction", void 0);
  48127. return HemisphericLight;
  48128. }(BABYLON.Light));
  48129. BABYLON.HemisphericLight = HemisphericLight;
  48130. })(BABYLON || (BABYLON = {}));
  48131. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48132. var BABYLON;
  48133. (function (BABYLON) {
  48134. /**
  48135. * Base implementation IShadowLight
  48136. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48137. */
  48138. var ShadowLight = /** @class */ (function (_super) {
  48139. __extends(ShadowLight, _super);
  48140. function ShadowLight() {
  48141. var _this = _super !== null && _super.apply(this, arguments) || this;
  48142. _this._needProjectionMatrixCompute = true;
  48143. return _this;
  48144. }
  48145. ShadowLight.prototype._setPosition = function (value) {
  48146. this._position = value;
  48147. };
  48148. Object.defineProperty(ShadowLight.prototype, "position", {
  48149. /**
  48150. * Sets the position the shadow will be casted from. Also use as the light position for both
  48151. * point and spot lights.
  48152. */
  48153. get: function () {
  48154. return this._position;
  48155. },
  48156. /**
  48157. * Sets the position the shadow will be casted from. Also use as the light position for both
  48158. * point and spot lights.
  48159. */
  48160. set: function (value) {
  48161. this._setPosition(value);
  48162. },
  48163. enumerable: true,
  48164. configurable: true
  48165. });
  48166. ShadowLight.prototype._setDirection = function (value) {
  48167. this._direction = value;
  48168. };
  48169. Object.defineProperty(ShadowLight.prototype, "direction", {
  48170. /**
  48171. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48172. * Also use as the light direction on spot and directional lights.
  48173. */
  48174. get: function () {
  48175. return this._direction;
  48176. },
  48177. /**
  48178. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48179. * Also use as the light direction on spot and directional lights.
  48180. */
  48181. set: function (value) {
  48182. this._setDirection(value);
  48183. },
  48184. enumerable: true,
  48185. configurable: true
  48186. });
  48187. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48188. /**
  48189. * Gets the shadow projection clipping minimum z value.
  48190. */
  48191. get: function () {
  48192. return this._shadowMinZ;
  48193. },
  48194. /**
  48195. * Sets the shadow projection clipping minimum z value.
  48196. */
  48197. set: function (value) {
  48198. this._shadowMinZ = value;
  48199. this.forceProjectionMatrixCompute();
  48200. },
  48201. enumerable: true,
  48202. configurable: true
  48203. });
  48204. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48205. /**
  48206. * Sets the shadow projection clipping maximum z value.
  48207. */
  48208. get: function () {
  48209. return this._shadowMaxZ;
  48210. },
  48211. /**
  48212. * Gets the shadow projection clipping maximum z value.
  48213. */
  48214. set: function (value) {
  48215. this._shadowMaxZ = value;
  48216. this.forceProjectionMatrixCompute();
  48217. },
  48218. enumerable: true,
  48219. configurable: true
  48220. });
  48221. /**
  48222. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48223. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48224. */
  48225. ShadowLight.prototype.computeTransformedInformation = function () {
  48226. if (this.parent && this.parent.getWorldMatrix) {
  48227. if (!this.transformedPosition) {
  48228. this.transformedPosition = BABYLON.Vector3.Zero();
  48229. }
  48230. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48231. // In case the direction is present.
  48232. if (this.direction) {
  48233. if (!this.transformedDirection) {
  48234. this.transformedDirection = BABYLON.Vector3.Zero();
  48235. }
  48236. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48237. }
  48238. return true;
  48239. }
  48240. return false;
  48241. };
  48242. /**
  48243. * Return the depth scale used for the shadow map.
  48244. * @returns the depth scale.
  48245. */
  48246. ShadowLight.prototype.getDepthScale = function () {
  48247. return 50.0;
  48248. };
  48249. /**
  48250. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48251. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48252. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48253. */
  48254. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48255. return this.transformedDirection ? this.transformedDirection : this.direction;
  48256. };
  48257. /**
  48258. * Returns the ShadowLight absolute position in the World.
  48259. * @returns the position vector in world space
  48260. */
  48261. ShadowLight.prototype.getAbsolutePosition = function () {
  48262. return this.transformedPosition ? this.transformedPosition : this.position;
  48263. };
  48264. /**
  48265. * Sets the ShadowLight direction toward the passed target.
  48266. * @param target The point tot target in local space
  48267. * @returns the updated ShadowLight direction
  48268. */
  48269. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48270. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48271. return this.direction;
  48272. };
  48273. /**
  48274. * Returns the light rotation in euler definition.
  48275. * @returns the x y z rotation in local space.
  48276. */
  48277. ShadowLight.prototype.getRotation = function () {
  48278. this.direction.normalize();
  48279. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48280. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48281. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48282. };
  48283. /**
  48284. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48285. * @returns true if a cube texture needs to be use
  48286. */
  48287. ShadowLight.prototype.needCube = function () {
  48288. return false;
  48289. };
  48290. /**
  48291. * Detects if the projection matrix requires to be recomputed this frame.
  48292. * @returns true if it requires to be recomputed otherwise, false.
  48293. */
  48294. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48295. return this._needProjectionMatrixCompute;
  48296. };
  48297. /**
  48298. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48299. */
  48300. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48301. this._needProjectionMatrixCompute = true;
  48302. };
  48303. /**
  48304. * Get the world matrix of the sahdow lights.
  48305. * @hidden Internal Use Only
  48306. */
  48307. ShadowLight.prototype._getWorldMatrix = function () {
  48308. if (!this._worldMatrix) {
  48309. this._worldMatrix = BABYLON.Matrix.Identity();
  48310. }
  48311. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48312. return this._worldMatrix;
  48313. };
  48314. /**
  48315. * Gets the minZ used for shadow according to both the scene and the light.
  48316. * @param activeCamera The camera we are returning the min for
  48317. * @returns the depth min z
  48318. */
  48319. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48320. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48321. };
  48322. /**
  48323. * Gets the maxZ used for shadow according to both the scene and the light.
  48324. * @param activeCamera The camera we are returning the max for
  48325. * @returns the depth max z
  48326. */
  48327. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48328. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48329. };
  48330. /**
  48331. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48332. * @param matrix The materix to updated with the projection information
  48333. * @param viewMatrix The transform matrix of the light
  48334. * @param renderList The list of mesh to render in the map
  48335. * @returns The current light
  48336. */
  48337. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48338. if (this.customProjectionMatrixBuilder) {
  48339. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48340. }
  48341. else {
  48342. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48343. }
  48344. return this;
  48345. };
  48346. __decorate([
  48347. BABYLON.serializeAsVector3()
  48348. ], ShadowLight.prototype, "position", null);
  48349. __decorate([
  48350. BABYLON.serializeAsVector3()
  48351. ], ShadowLight.prototype, "direction", null);
  48352. __decorate([
  48353. BABYLON.serialize()
  48354. ], ShadowLight.prototype, "shadowMinZ", null);
  48355. __decorate([
  48356. BABYLON.serialize()
  48357. ], ShadowLight.prototype, "shadowMaxZ", null);
  48358. return ShadowLight;
  48359. }(BABYLON.Light));
  48360. BABYLON.ShadowLight = ShadowLight;
  48361. })(BABYLON || (BABYLON = {}));
  48362. //# sourceMappingURL=babylon.shadowLight.js.map
  48363. var BABYLON;
  48364. (function (BABYLON) {
  48365. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48366. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48367. });
  48368. /**
  48369. * A point light is a light defined by an unique point in world space.
  48370. * The light is emitted in every direction from this point.
  48371. * A good example of a point light is a standard light bulb.
  48372. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48373. */
  48374. var PointLight = /** @class */ (function (_super) {
  48375. __extends(PointLight, _super);
  48376. /**
  48377. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48378. * A PointLight emits the light in every direction.
  48379. * It can cast shadows.
  48380. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48381. * ```javascript
  48382. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48383. * ```
  48384. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48385. * @param name The light friendly name
  48386. * @param position The position of the point light in the scene
  48387. * @param scene The scene the lights belongs to
  48388. */
  48389. function PointLight(name, position, scene) {
  48390. var _this = _super.call(this, name, scene) || this;
  48391. _this._shadowAngle = Math.PI / 2;
  48392. _this.position = position;
  48393. return _this;
  48394. }
  48395. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48396. /**
  48397. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48398. * This specifies what angle the shadow will use to be created.
  48399. *
  48400. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48401. */
  48402. get: function () {
  48403. return this._shadowAngle;
  48404. },
  48405. /**
  48406. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48407. * This specifies what angle the shadow will use to be created.
  48408. *
  48409. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48410. */
  48411. set: function (value) {
  48412. this._shadowAngle = value;
  48413. this.forceProjectionMatrixCompute();
  48414. },
  48415. enumerable: true,
  48416. configurable: true
  48417. });
  48418. Object.defineProperty(PointLight.prototype, "direction", {
  48419. /**
  48420. * Gets the direction if it has been set.
  48421. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48422. */
  48423. get: function () {
  48424. return this._direction;
  48425. },
  48426. /**
  48427. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48428. */
  48429. set: function (value) {
  48430. var previousNeedCube = this.needCube();
  48431. this._direction = value;
  48432. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48433. this._shadowGenerator.recreateShadowMap();
  48434. }
  48435. },
  48436. enumerable: true,
  48437. configurable: true
  48438. });
  48439. /**
  48440. * Returns the string "PointLight"
  48441. * @returns the class name
  48442. */
  48443. PointLight.prototype.getClassName = function () {
  48444. return "PointLight";
  48445. };
  48446. /**
  48447. * Returns the integer 0.
  48448. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48449. */
  48450. PointLight.prototype.getTypeID = function () {
  48451. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48452. };
  48453. /**
  48454. * Specifies wether or not the shadowmap should be a cube texture.
  48455. * @returns true if the shadowmap needs to be a cube texture.
  48456. */
  48457. PointLight.prototype.needCube = function () {
  48458. return !this.direction;
  48459. };
  48460. /**
  48461. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48462. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48463. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48464. */
  48465. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48466. if (this.direction) {
  48467. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48468. }
  48469. else {
  48470. switch (faceIndex) {
  48471. case 0:
  48472. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48473. case 1:
  48474. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48475. case 2:
  48476. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48477. case 3:
  48478. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48479. case 4:
  48480. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48481. case 5:
  48482. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48483. }
  48484. }
  48485. return BABYLON.Vector3.Zero();
  48486. };
  48487. /**
  48488. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48489. * - fov = PI / 2
  48490. * - aspect ratio : 1.0
  48491. * - z-near and far equal to the active camera minZ and maxZ.
  48492. * Returns the PointLight.
  48493. */
  48494. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48495. var activeCamera = this.getScene().activeCamera;
  48496. if (!activeCamera) {
  48497. return;
  48498. }
  48499. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48500. };
  48501. PointLight.prototype._buildUniformLayout = function () {
  48502. this._uniformBuffer.addUniform("vLightData", 4);
  48503. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48504. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48505. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48506. this._uniformBuffer.addUniform("depthValues", 2);
  48507. this._uniformBuffer.create();
  48508. };
  48509. /**
  48510. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48511. * @param effect The effect to update
  48512. * @param lightIndex The index of the light in the effect to update
  48513. * @returns The point light
  48514. */
  48515. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48516. if (this.computeTransformedInformation()) {
  48517. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48518. return this;
  48519. }
  48520. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48521. return this;
  48522. };
  48523. /**
  48524. * Prepares the list of defines specific to the light type.
  48525. * @param defines the list of defines
  48526. * @param lightIndex defines the index of the light for the effect
  48527. */
  48528. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48529. defines["POINTLIGHT" + lightIndex] = true;
  48530. };
  48531. __decorate([
  48532. BABYLON.serialize()
  48533. ], PointLight.prototype, "shadowAngle", null);
  48534. return PointLight;
  48535. }(BABYLON.ShadowLight));
  48536. BABYLON.PointLight = PointLight;
  48537. })(BABYLON || (BABYLON = {}));
  48538. //# sourceMappingURL=babylon.pointLight.js.map
  48539. var BABYLON;
  48540. (function (BABYLON) {
  48541. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48542. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48543. });
  48544. /**
  48545. * A directional light is defined by a direction (what a surprise!).
  48546. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48547. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  48548. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48549. */
  48550. var DirectionalLight = /** @class */ (function (_super) {
  48551. __extends(DirectionalLight, _super);
  48552. /**
  48553. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48554. * The directional light is emitted from everywhere in the given direction.
  48555. * It can cast shawdows.
  48556. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48557. * @param name The friendly name of the light
  48558. * @param direction The direction of the light
  48559. * @param scene The scene the light belongs to
  48560. */
  48561. function DirectionalLight(name, direction, scene) {
  48562. var _this = _super.call(this, name, scene) || this;
  48563. _this._shadowFrustumSize = 0;
  48564. _this._shadowOrthoScale = 0.1;
  48565. /**
  48566. * Automatically compute the projection matrix to best fit (including all the casters)
  48567. * on each frame.
  48568. */
  48569. _this.autoUpdateExtends = true;
  48570. // Cache
  48571. _this._orthoLeft = Number.MAX_VALUE;
  48572. _this._orthoRight = Number.MIN_VALUE;
  48573. _this._orthoTop = Number.MIN_VALUE;
  48574. _this._orthoBottom = Number.MAX_VALUE;
  48575. _this.position = direction.scale(-1.0);
  48576. _this.direction = direction;
  48577. return _this;
  48578. }
  48579. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48580. /**
  48581. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48582. */
  48583. get: function () {
  48584. return this._shadowFrustumSize;
  48585. },
  48586. /**
  48587. * Specifies a fix frustum size for the shadow generation.
  48588. */
  48589. set: function (value) {
  48590. this._shadowFrustumSize = value;
  48591. this.forceProjectionMatrixCompute();
  48592. },
  48593. enumerable: true,
  48594. configurable: true
  48595. });
  48596. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48597. /**
  48598. * Gets the shadow projection scale against the optimal computed one.
  48599. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48600. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48601. */
  48602. get: function () {
  48603. return this._shadowOrthoScale;
  48604. },
  48605. /**
  48606. * Sets the shadow projection scale against the optimal computed one.
  48607. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48608. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48609. */
  48610. set: function (value) {
  48611. this._shadowOrthoScale = value;
  48612. this.forceProjectionMatrixCompute();
  48613. },
  48614. enumerable: true,
  48615. configurable: true
  48616. });
  48617. /**
  48618. * Returns the string "DirectionalLight".
  48619. * @return The class name
  48620. */
  48621. DirectionalLight.prototype.getClassName = function () {
  48622. return "DirectionalLight";
  48623. };
  48624. /**
  48625. * Returns the integer 1.
  48626. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48627. */
  48628. DirectionalLight.prototype.getTypeID = function () {
  48629. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48630. };
  48631. /**
  48632. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48633. * Returns the DirectionalLight Shadow projection matrix.
  48634. */
  48635. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48636. if (this.shadowFrustumSize > 0) {
  48637. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48638. }
  48639. else {
  48640. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48641. }
  48642. };
  48643. /**
  48644. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48645. * Returns the DirectionalLight Shadow projection matrix.
  48646. */
  48647. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48648. var activeCamera = this.getScene().activeCamera;
  48649. if (!activeCamera) {
  48650. return;
  48651. }
  48652. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48653. };
  48654. /**
  48655. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48656. * Returns the DirectionalLight Shadow projection matrix.
  48657. */
  48658. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48659. var activeCamera = this.getScene().activeCamera;
  48660. if (!activeCamera) {
  48661. return;
  48662. }
  48663. // Check extends
  48664. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48665. var tempVector3 = BABYLON.Vector3.Zero();
  48666. this._orthoLeft = Number.MAX_VALUE;
  48667. this._orthoRight = Number.MIN_VALUE;
  48668. this._orthoTop = Number.MIN_VALUE;
  48669. this._orthoBottom = Number.MAX_VALUE;
  48670. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48671. var mesh = renderList[meshIndex];
  48672. if (!mesh) {
  48673. continue;
  48674. }
  48675. var boundingInfo = mesh.getBoundingInfo();
  48676. var boundingBox = boundingInfo.boundingBox;
  48677. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48678. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48679. if (tempVector3.x < this._orthoLeft)
  48680. this._orthoLeft = tempVector3.x;
  48681. if (tempVector3.y < this._orthoBottom)
  48682. this._orthoBottom = tempVector3.y;
  48683. if (tempVector3.x > this._orthoRight)
  48684. this._orthoRight = tempVector3.x;
  48685. if (tempVector3.y > this._orthoTop)
  48686. this._orthoTop = tempVector3.y;
  48687. }
  48688. }
  48689. }
  48690. var xOffset = this._orthoRight - this._orthoLeft;
  48691. var yOffset = this._orthoTop - this._orthoBottom;
  48692. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48693. };
  48694. DirectionalLight.prototype._buildUniformLayout = function () {
  48695. this._uniformBuffer.addUniform("vLightData", 4);
  48696. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48697. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48698. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48699. this._uniformBuffer.addUniform("depthValues", 2);
  48700. this._uniformBuffer.create();
  48701. };
  48702. /**
  48703. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48704. * @param effect The effect to update
  48705. * @param lightIndex The index of the light in the effect to update
  48706. * @returns The directional light
  48707. */
  48708. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48709. if (this.computeTransformedInformation()) {
  48710. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48711. return this;
  48712. }
  48713. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48714. return this;
  48715. };
  48716. /**
  48717. * Gets the minZ used for shadow according to both the scene and the light.
  48718. *
  48719. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48720. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48721. * @param activeCamera The camera we are returning the min for
  48722. * @returns the depth min z
  48723. */
  48724. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48725. return 1;
  48726. };
  48727. /**
  48728. * Gets the maxZ used for shadow according to both the scene and the light.
  48729. *
  48730. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48731. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48732. * @param activeCamera The camera we are returning the max for
  48733. * @returns the depth max z
  48734. */
  48735. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48736. return 1;
  48737. };
  48738. /**
  48739. * Prepares the list of defines specific to the light type.
  48740. * @param defines the list of defines
  48741. * @param lightIndex defines the index of the light for the effect
  48742. */
  48743. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48744. defines["DIRLIGHT" + lightIndex] = true;
  48745. };
  48746. __decorate([
  48747. BABYLON.serialize()
  48748. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48749. __decorate([
  48750. BABYLON.serialize()
  48751. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48752. __decorate([
  48753. BABYLON.serialize()
  48754. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48755. return DirectionalLight;
  48756. }(BABYLON.ShadowLight));
  48757. BABYLON.DirectionalLight = DirectionalLight;
  48758. })(BABYLON || (BABYLON = {}));
  48759. //# sourceMappingURL=babylon.directionalLight.js.map
  48760. var BABYLON;
  48761. (function (BABYLON) {
  48762. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48763. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48764. });
  48765. /**
  48766. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48767. * These values define a cone of light starting from the position, emitting toward the direction.
  48768. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48769. * and the exponent defines the speed of the decay of the light with distance (reach).
  48770. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48771. */
  48772. var SpotLight = /** @class */ (function (_super) {
  48773. __extends(SpotLight, _super);
  48774. /**
  48775. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48776. * It can cast shadows.
  48777. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48778. * @param name The light friendly name
  48779. * @param position The position of the spot light in the scene
  48780. * @param direction The direction of the light in the scene
  48781. * @param angle The cone angle of the light in Radians
  48782. * @param exponent The light decay speed with the distance from the emission spot
  48783. * @param scene The scene the lights belongs to
  48784. */
  48785. function SpotLight(name, position, direction, angle, exponent, scene) {
  48786. var _this = _super.call(this, name, scene) || this;
  48787. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48788. _this._projectionTextureLightNear = 1e-6;
  48789. _this._projectionTextureLightFar = 1000.0;
  48790. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48791. _this._projectionTextureViewLightDirty = true;
  48792. _this._projectionTextureProjectionLightDirty = true;
  48793. _this._projectionTextureDirty = true;
  48794. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48795. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48796. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48797. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  48798. _this.position = position;
  48799. _this.direction = direction;
  48800. _this.angle = angle;
  48801. _this.exponent = exponent;
  48802. return _this;
  48803. }
  48804. Object.defineProperty(SpotLight.prototype, "angle", {
  48805. /**
  48806. * Gets the cone angle of the spot light in Radians.
  48807. */
  48808. get: function () {
  48809. return this._angle;
  48810. },
  48811. /**
  48812. * Sets the cone angle of the spot light in Radians.
  48813. */
  48814. set: function (value) {
  48815. this._angle = value;
  48816. this._projectionTextureProjectionLightDirty = true;
  48817. this.forceProjectionMatrixCompute();
  48818. },
  48819. enumerable: true,
  48820. configurable: true
  48821. });
  48822. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48823. /**
  48824. * Allows scaling the angle of the light for shadow generation only.
  48825. */
  48826. get: function () {
  48827. return this._shadowAngleScale;
  48828. },
  48829. /**
  48830. * Allows scaling the angle of the light for shadow generation only.
  48831. */
  48832. set: function (value) {
  48833. this._shadowAngleScale = value;
  48834. this.forceProjectionMatrixCompute();
  48835. },
  48836. enumerable: true,
  48837. configurable: true
  48838. });
  48839. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48840. /**
  48841. * Allows reading the projecton texture
  48842. */
  48843. get: function () {
  48844. return this._projectionTextureMatrix;
  48845. },
  48846. enumerable: true,
  48847. configurable: true
  48848. });
  48849. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48850. /**
  48851. * Gets the near clip of the Spotlight for texture projection.
  48852. */
  48853. get: function () {
  48854. return this._projectionTextureLightNear;
  48855. },
  48856. /**
  48857. * Sets the near clip of the Spotlight for texture projection.
  48858. */
  48859. set: function (value) {
  48860. this._projectionTextureLightNear = value;
  48861. this._projectionTextureProjectionLightDirty = true;
  48862. },
  48863. enumerable: true,
  48864. configurable: true
  48865. });
  48866. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48867. /**
  48868. * Gets the far clip of the Spotlight for texture projection.
  48869. */
  48870. get: function () {
  48871. return this._projectionTextureLightFar;
  48872. },
  48873. /**
  48874. * Sets the far clip of the Spotlight for texture projection.
  48875. */
  48876. set: function (value) {
  48877. this._projectionTextureLightFar = value;
  48878. this._projectionTextureProjectionLightDirty = true;
  48879. },
  48880. enumerable: true,
  48881. configurable: true
  48882. });
  48883. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48884. /**
  48885. * Gets the Up vector of the Spotlight for texture projection.
  48886. */
  48887. get: function () {
  48888. return this._projectionTextureUpDirection;
  48889. },
  48890. /**
  48891. * Sets the Up vector of the Spotlight for texture projection.
  48892. */
  48893. set: function (value) {
  48894. this._projectionTextureUpDirection = value;
  48895. this._projectionTextureProjectionLightDirty = true;
  48896. },
  48897. enumerable: true,
  48898. configurable: true
  48899. });
  48900. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48901. /**
  48902. * Gets the projection texture of the light.
  48903. */
  48904. get: function () {
  48905. return this._projectionTexture;
  48906. },
  48907. /**
  48908. * Sets the projection texture of the light.
  48909. */
  48910. set: function (value) {
  48911. this._projectionTexture = value;
  48912. this._projectionTextureDirty = true;
  48913. },
  48914. enumerable: true,
  48915. configurable: true
  48916. });
  48917. /**
  48918. * Returns the string "SpotLight".
  48919. * @returns the class name
  48920. */
  48921. SpotLight.prototype.getClassName = function () {
  48922. return "SpotLight";
  48923. };
  48924. /**
  48925. * Returns the integer 2.
  48926. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48927. */
  48928. SpotLight.prototype.getTypeID = function () {
  48929. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48930. };
  48931. /**
  48932. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48933. */
  48934. SpotLight.prototype._setDirection = function (value) {
  48935. _super.prototype._setDirection.call(this, value);
  48936. this._projectionTextureViewLightDirty = true;
  48937. };
  48938. /**
  48939. * Overrides the position setter to recompute the projection texture view light Matrix.
  48940. */
  48941. SpotLight.prototype._setPosition = function (value) {
  48942. _super.prototype._setPosition.call(this, value);
  48943. this._projectionTextureViewLightDirty = true;
  48944. };
  48945. /**
  48946. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  48947. * Returns the SpotLight.
  48948. */
  48949. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48950. var activeCamera = this.getScene().activeCamera;
  48951. if (!activeCamera) {
  48952. return;
  48953. }
  48954. this._shadowAngleScale = this._shadowAngleScale || 1;
  48955. var angle = this._shadowAngleScale * this._angle;
  48956. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48957. };
  48958. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48959. this._projectionTextureViewLightDirty = false;
  48960. this._projectionTextureDirty = true;
  48961. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48962. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48963. };
  48964. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48965. this._projectionTextureProjectionLightDirty = false;
  48966. this._projectionTextureDirty = true;
  48967. var light_far = this.projectionTextureLightFar;
  48968. var light_near = this.projectionTextureLightNear;
  48969. var P = light_far / (light_far - light_near);
  48970. var Q = -P * light_near;
  48971. var S = 1.0 / Math.tan(this._angle / 2.0);
  48972. var A = 1.0;
  48973. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  48974. };
  48975. /**
  48976. * Main function for light texture projection matrix computing.
  48977. */
  48978. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48979. this._projectionTextureDirty = false;
  48980. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48981. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48982. };
  48983. SpotLight.prototype._buildUniformLayout = function () {
  48984. this._uniformBuffer.addUniform("vLightData", 4);
  48985. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48986. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48987. this._uniformBuffer.addUniform("vLightDirection", 3);
  48988. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48989. this._uniformBuffer.addUniform("depthValues", 2);
  48990. this._uniformBuffer.create();
  48991. };
  48992. /**
  48993. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  48994. * @param effect The effect to update
  48995. * @param lightIndex The index of the light in the effect to update
  48996. * @returns The spot light
  48997. */
  48998. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  48999. var normalizeDirection;
  49000. if (this.computeTransformedInformation()) {
  49001. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49002. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49003. }
  49004. else {
  49005. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49006. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49007. }
  49008. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49009. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49010. if (this._projectionTextureViewLightDirty) {
  49011. this._computeProjectionTextureViewLightMatrix();
  49012. }
  49013. if (this._projectionTextureProjectionLightDirty) {
  49014. this._computeProjectionTextureProjectionLightMatrix();
  49015. }
  49016. if (this._projectionTextureDirty) {
  49017. this._computeProjectionTextureMatrix();
  49018. }
  49019. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49020. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49021. }
  49022. return this;
  49023. };
  49024. /**
  49025. * Disposes the light and the associated resources.
  49026. */
  49027. SpotLight.prototype.dispose = function () {
  49028. _super.prototype.dispose.call(this);
  49029. if (this._projectionTexture) {
  49030. this._projectionTexture.dispose();
  49031. }
  49032. };
  49033. /**
  49034. * Prepares the list of defines specific to the light type.
  49035. * @param defines the list of defines
  49036. * @param lightIndex defines the index of the light for the effect
  49037. */
  49038. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49039. defines["SPOTLIGHT" + lightIndex] = true;
  49040. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49041. };
  49042. __decorate([
  49043. BABYLON.serialize()
  49044. ], SpotLight.prototype, "angle", null);
  49045. __decorate([
  49046. BABYLON.serialize()
  49047. ], SpotLight.prototype, "shadowAngleScale", null);
  49048. __decorate([
  49049. BABYLON.serialize()
  49050. ], SpotLight.prototype, "exponent", void 0);
  49051. __decorate([
  49052. BABYLON.serialize()
  49053. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49054. __decorate([
  49055. BABYLON.serialize()
  49056. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49057. __decorate([
  49058. BABYLON.serialize()
  49059. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49060. __decorate([
  49061. BABYLON.serializeAsTexture("projectedLightTexture")
  49062. ], SpotLight.prototype, "_projectionTexture", void 0);
  49063. return SpotLight;
  49064. }(BABYLON.ShadowLight));
  49065. BABYLON.SpotLight = SpotLight;
  49066. })(BABYLON || (BABYLON = {}));
  49067. //# sourceMappingURL=babylon.spotLight.js.map
  49068. var BABYLON;
  49069. (function (BABYLON) {
  49070. /**
  49071. * Class used to override all child animations of a given target
  49072. */
  49073. var AnimationPropertiesOverride = /** @class */ (function () {
  49074. function AnimationPropertiesOverride() {
  49075. /**
  49076. * Gets or sets a value indicating if animation blending must be used
  49077. */
  49078. this.enableBlending = false;
  49079. /**
  49080. * Gets or sets the blending speed to use when enableBlending is true
  49081. */
  49082. this.blendingSpeed = 0.01;
  49083. /**
  49084. * Gets or sets the default loop mode to use
  49085. */
  49086. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49087. }
  49088. return AnimationPropertiesOverride;
  49089. }());
  49090. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49091. })(BABYLON || (BABYLON = {}));
  49092. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49093. var BABYLON;
  49094. (function (BABYLON) {
  49095. /**
  49096. * Represents the range of an animation
  49097. */
  49098. var AnimationRange = /** @class */ (function () {
  49099. /**
  49100. * Initializes the range of an animation
  49101. * @param name The name of the animation range
  49102. * @param from The starting frame of the animation
  49103. * @param to The ending frame of the animation
  49104. */
  49105. function AnimationRange(
  49106. /**The name of the animation range**/
  49107. name,
  49108. /**The starting frame of the animation */
  49109. from,
  49110. /**The ending frame of the animation*/
  49111. to) {
  49112. this.name = name;
  49113. this.from = from;
  49114. this.to = to;
  49115. }
  49116. /**
  49117. * Makes a copy of the animation range
  49118. * @returns A copy of the animation range
  49119. */
  49120. AnimationRange.prototype.clone = function () {
  49121. return new AnimationRange(this.name, this.from, this.to);
  49122. };
  49123. return AnimationRange;
  49124. }());
  49125. BABYLON.AnimationRange = AnimationRange;
  49126. /**
  49127. * Composed of a frame, and an action function
  49128. */
  49129. var AnimationEvent = /** @class */ (function () {
  49130. /**
  49131. * Initializes the animation event
  49132. * @param frame The frame for which the event is triggered
  49133. * @param action The event to perform when triggered
  49134. * @param onlyOnce Specifies if the event should be triggered only once
  49135. */
  49136. function AnimationEvent(
  49137. /** The frame for which the event is triggered **/
  49138. frame,
  49139. /** The event to perform when triggered **/
  49140. action,
  49141. /** Specifies if the event should be triggered only once**/
  49142. onlyOnce) {
  49143. this.frame = frame;
  49144. this.action = action;
  49145. this.onlyOnce = onlyOnce;
  49146. /**
  49147. * Specifies if the animation event is done
  49148. */
  49149. this.isDone = false;
  49150. }
  49151. /** @hidden */
  49152. AnimationEvent.prototype._clone = function () {
  49153. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49154. };
  49155. return AnimationEvent;
  49156. }());
  49157. BABYLON.AnimationEvent = AnimationEvent;
  49158. /**
  49159. * A cursor which tracks a point on a path
  49160. */
  49161. var PathCursor = /** @class */ (function () {
  49162. /**
  49163. * Initializes the path cursor
  49164. * @param path The path to track
  49165. */
  49166. function PathCursor(path) {
  49167. this.path = path;
  49168. /**
  49169. * Stores path cursor callbacks for when an onchange event is triggered
  49170. */
  49171. this._onchange = new Array();
  49172. /**
  49173. * The value of the path cursor
  49174. */
  49175. this.value = 0;
  49176. /**
  49177. * The animation array of the path cursor
  49178. */
  49179. this.animations = new Array();
  49180. }
  49181. /**
  49182. * Gets the cursor point on the path
  49183. * @returns A point on the path cursor at the cursor location
  49184. */
  49185. PathCursor.prototype.getPoint = function () {
  49186. var point = this.path.getPointAtLengthPosition(this.value);
  49187. return new BABYLON.Vector3(point.x, 0, point.y);
  49188. };
  49189. /**
  49190. * Moves the cursor ahead by the step amount
  49191. * @param step The amount to move the cursor forward
  49192. * @returns This path cursor
  49193. */
  49194. PathCursor.prototype.moveAhead = function (step) {
  49195. if (step === void 0) { step = 0.002; }
  49196. this.move(step);
  49197. return this;
  49198. };
  49199. /**
  49200. * Moves the cursor behind by the step amount
  49201. * @param step The amount to move the cursor back
  49202. * @returns This path cursor
  49203. */
  49204. PathCursor.prototype.moveBack = function (step) {
  49205. if (step === void 0) { step = 0.002; }
  49206. this.move(-step);
  49207. return this;
  49208. };
  49209. /**
  49210. * Moves the cursor by the step amount
  49211. * If the step amount is greater than one, an exception is thrown
  49212. * @param step The amount to move the cursor
  49213. * @returns This path cursor
  49214. */
  49215. PathCursor.prototype.move = function (step) {
  49216. if (Math.abs(step) > 1) {
  49217. throw "step size should be less than 1.";
  49218. }
  49219. this.value += step;
  49220. this.ensureLimits();
  49221. this.raiseOnChange();
  49222. return this;
  49223. };
  49224. /**
  49225. * Ensures that the value is limited between zero and one
  49226. * @returns This path cursor
  49227. */
  49228. PathCursor.prototype.ensureLimits = function () {
  49229. while (this.value > 1) {
  49230. this.value -= 1;
  49231. }
  49232. while (this.value < 0) {
  49233. this.value += 1;
  49234. }
  49235. return this;
  49236. };
  49237. /**
  49238. * Runs onchange callbacks on change (used by the animation engine)
  49239. * @returns This path cursor
  49240. */
  49241. PathCursor.prototype.raiseOnChange = function () {
  49242. var _this = this;
  49243. this._onchange.forEach(function (f) { return f(_this); });
  49244. return this;
  49245. };
  49246. /**
  49247. * Executes a function on change
  49248. * @param f A path cursor onchange callback
  49249. * @returns This path cursor
  49250. */
  49251. PathCursor.prototype.onchange = function (f) {
  49252. this._onchange.push(f);
  49253. return this;
  49254. };
  49255. return PathCursor;
  49256. }());
  49257. BABYLON.PathCursor = PathCursor;
  49258. /**
  49259. * Enum for the animation key frame interpolation type
  49260. */
  49261. var AnimationKeyInterpolation;
  49262. (function (AnimationKeyInterpolation) {
  49263. /**
  49264. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49265. */
  49266. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49267. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49268. /**
  49269. * Class used to store any kind of animation
  49270. */
  49271. var Animation = /** @class */ (function () {
  49272. /**
  49273. * Initializes the animation
  49274. * @param name Name of the animation
  49275. * @param targetProperty Property to animate
  49276. * @param framePerSecond The frames per second of the animation
  49277. * @param dataType The data type of the animation
  49278. * @param loopMode The loop mode of the animation
  49279. * @param enableBlendings Specifies if blending should be enabled
  49280. */
  49281. function Animation(
  49282. /**Name of the animation */
  49283. name,
  49284. /**Property to animate */
  49285. targetProperty,
  49286. /**The frames per second of the animation */
  49287. framePerSecond,
  49288. /**The data type of the animation */
  49289. dataType,
  49290. /**The loop mode of the animation */
  49291. loopMode,
  49292. /**Specifies if blending should be enabled */
  49293. enableBlending) {
  49294. this.name = name;
  49295. this.targetProperty = targetProperty;
  49296. this.framePerSecond = framePerSecond;
  49297. this.dataType = dataType;
  49298. this.loopMode = loopMode;
  49299. this.enableBlending = enableBlending;
  49300. /**
  49301. * @hidden Internal use only
  49302. */
  49303. this._runtimeAnimations = new Array();
  49304. /**
  49305. * The set of event that will be linked to this animation
  49306. */
  49307. this._events = new Array();
  49308. /**
  49309. * Stores the blending speed of the animation
  49310. */
  49311. this.blendingSpeed = 0.01;
  49312. /**
  49313. * Stores the animation ranges for the animation
  49314. */
  49315. this._ranges = {};
  49316. this.targetPropertyPath = targetProperty.split(".");
  49317. this.dataType = dataType;
  49318. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49319. }
  49320. /**
  49321. * @hidden Internal use
  49322. */
  49323. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49324. var dataType = undefined;
  49325. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49326. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49327. }
  49328. else if (from instanceof BABYLON.Quaternion) {
  49329. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49330. }
  49331. else if (from instanceof BABYLON.Vector3) {
  49332. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49333. }
  49334. else if (from instanceof BABYLON.Vector2) {
  49335. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49336. }
  49337. else if (from instanceof BABYLON.Color3) {
  49338. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49339. }
  49340. else if (from instanceof BABYLON.Size) {
  49341. dataType = Animation.ANIMATIONTYPE_SIZE;
  49342. }
  49343. if (dataType == undefined) {
  49344. return null;
  49345. }
  49346. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49347. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49348. animation.setKeys(keys);
  49349. if (easingFunction !== undefined) {
  49350. animation.setEasingFunction(easingFunction);
  49351. }
  49352. return animation;
  49353. };
  49354. /**
  49355. * Sets up an animation
  49356. * @param property The property to animate
  49357. * @param animationType The animation type to apply
  49358. * @param framePerSecond The frames per second of the animation
  49359. * @param easingFunction The easing function used in the animation
  49360. * @returns The created animation
  49361. */
  49362. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49363. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49364. animation.setEasingFunction(easingFunction);
  49365. return animation;
  49366. };
  49367. /**
  49368. * Create and start an animation on a node
  49369. * @param name defines the name of the global animation that will be run on all nodes
  49370. * @param node defines the root node where the animation will take place
  49371. * @param targetProperty defines property to animate
  49372. * @param framePerSecond defines the number of frame per second yo use
  49373. * @param totalFrame defines the number of frames in total
  49374. * @param from defines the initial value
  49375. * @param to defines the final value
  49376. * @param loopMode defines which loop mode you want to use (off by default)
  49377. * @param easingFunction defines the easing function to use (linear by default)
  49378. * @param onAnimationEnd defines the callback to call when animation end
  49379. * @returns the animatable created for this animation
  49380. */
  49381. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49382. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49383. if (!animation) {
  49384. return null;
  49385. }
  49386. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49387. };
  49388. /**
  49389. * Create and start an animation on a node and its descendants
  49390. * @param name defines the name of the global animation that will be run on all nodes
  49391. * @param node defines the root node where the animation will take place
  49392. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  49393. * @param targetProperty defines property to animate
  49394. * @param framePerSecond defines the number of frame per second to use
  49395. * @param totalFrame defines the number of frames in total
  49396. * @param from defines the initial value
  49397. * @param to defines the final value
  49398. * @param loopMode defines which loop mode you want to use (off by default)
  49399. * @param easingFunction defines the easing function to use (linear by default)
  49400. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49401. * @returns the list of animatables created for all nodes
  49402. * @example https://www.babylonjs-playground.com/#MH0VLI
  49403. */
  49404. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49405. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49406. if (!animation) {
  49407. return null;
  49408. }
  49409. var scene = node.getScene();
  49410. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49411. };
  49412. /**
  49413. * Creates a new animation, merges it with the existing animations and starts it
  49414. * @param name Name of the animation
  49415. * @param node Node which contains the scene that begins the animations
  49416. * @param targetProperty Specifies which property to animate
  49417. * @param framePerSecond The frames per second of the animation
  49418. * @param totalFrame The total number of frames
  49419. * @param from The frame at the beginning of the animation
  49420. * @param to The frame at the end of the animation
  49421. * @param loopMode Specifies the loop mode of the animation
  49422. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49423. * @param onAnimationEnd Callback to run once the animation is complete
  49424. * @returns Nullable animation
  49425. */
  49426. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49427. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49428. if (!animation) {
  49429. return null;
  49430. }
  49431. node.animations.push(animation);
  49432. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49433. };
  49434. /**
  49435. * Transition property of an host to the target Value
  49436. * @param property The property to transition
  49437. * @param targetValue The target Value of the property
  49438. * @param host The object where the property to animate belongs
  49439. * @param scene Scene used to run the animation
  49440. * @param frameRate Framerate (in frame/s) to use
  49441. * @param transition The transition type we want to use
  49442. * @param duration The duration of the animation, in milliseconds
  49443. * @param onAnimationEnd Callback trigger at the end of the animation
  49444. * @returns Nullable animation
  49445. */
  49446. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49447. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49448. if (duration <= 0) {
  49449. host[property] = targetValue;
  49450. if (onAnimationEnd) {
  49451. onAnimationEnd();
  49452. }
  49453. return null;
  49454. }
  49455. var endFrame = frameRate * (duration / 1000);
  49456. transition.setKeys([{
  49457. frame: 0,
  49458. value: host[property].clone ? host[property].clone() : host[property]
  49459. },
  49460. {
  49461. frame: endFrame,
  49462. value: targetValue
  49463. }]);
  49464. if (!host.animations) {
  49465. host.animations = [];
  49466. }
  49467. host.animations.push(transition);
  49468. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49469. animation.onAnimationEnd = onAnimationEnd;
  49470. return animation;
  49471. };
  49472. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49473. /**
  49474. * Return the array of runtime animations currently using this animation
  49475. */
  49476. get: function () {
  49477. return this._runtimeAnimations;
  49478. },
  49479. enumerable: true,
  49480. configurable: true
  49481. });
  49482. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49483. /**
  49484. * Specifies if any of the runtime animations are currently running
  49485. */
  49486. get: function () {
  49487. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49488. var runtimeAnimation = _a[_i];
  49489. if (!runtimeAnimation.isStopped) {
  49490. return true;
  49491. }
  49492. }
  49493. return false;
  49494. },
  49495. enumerable: true,
  49496. configurable: true
  49497. });
  49498. // Methods
  49499. /**
  49500. * Converts the animation to a string
  49501. * @param fullDetails support for multiple levels of logging within scene loading
  49502. * @returns String form of the animation
  49503. */
  49504. Animation.prototype.toString = function (fullDetails) {
  49505. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49506. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49507. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49508. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49509. if (fullDetails) {
  49510. ret += ", Ranges: {";
  49511. var first = true;
  49512. for (var name in this._ranges) {
  49513. if (first) {
  49514. ret += ", ";
  49515. first = false;
  49516. }
  49517. ret += name;
  49518. }
  49519. ret += "}";
  49520. }
  49521. return ret;
  49522. };
  49523. /**
  49524. * Add an event to this animation
  49525. * @param event Event to add
  49526. */
  49527. Animation.prototype.addEvent = function (event) {
  49528. this._events.push(event);
  49529. };
  49530. /**
  49531. * Remove all events found at the given frame
  49532. * @param frame The frame to remove events from
  49533. */
  49534. Animation.prototype.removeEvents = function (frame) {
  49535. for (var index = 0; index < this._events.length; index++) {
  49536. if (this._events[index].frame === frame) {
  49537. this._events.splice(index, 1);
  49538. index--;
  49539. }
  49540. }
  49541. };
  49542. /**
  49543. * Retrieves all the events from the animation
  49544. * @returns Events from the animation
  49545. */
  49546. Animation.prototype.getEvents = function () {
  49547. return this._events;
  49548. };
  49549. /**
  49550. * Creates an animation range
  49551. * @param name Name of the animation range
  49552. * @param from Starting frame of the animation range
  49553. * @param to Ending frame of the animation
  49554. */
  49555. Animation.prototype.createRange = function (name, from, to) {
  49556. // check name not already in use; could happen for bones after serialized
  49557. if (!this._ranges[name]) {
  49558. this._ranges[name] = new AnimationRange(name, from, to);
  49559. }
  49560. };
  49561. /**
  49562. * Deletes an animation range by name
  49563. * @param name Name of the animation range to delete
  49564. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49565. */
  49566. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49567. if (deleteFrames === void 0) { deleteFrames = true; }
  49568. var range = this._ranges[name];
  49569. if (!range) {
  49570. return;
  49571. }
  49572. if (deleteFrames) {
  49573. var from = range.from;
  49574. var to = range.to;
  49575. // this loop MUST go high to low for multiple splices to work
  49576. for (var key = this._keys.length - 1; key >= 0; key--) {
  49577. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49578. this._keys.splice(key, 1);
  49579. }
  49580. }
  49581. }
  49582. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49583. };
  49584. /**
  49585. * Gets the animation range by name, or null if not defined
  49586. * @param name Name of the animation range
  49587. * @returns Nullable animation range
  49588. */
  49589. Animation.prototype.getRange = function (name) {
  49590. return this._ranges[name];
  49591. };
  49592. /**
  49593. * Gets the key frames from the animation
  49594. * @returns The key frames of the animation
  49595. */
  49596. Animation.prototype.getKeys = function () {
  49597. return this._keys;
  49598. };
  49599. /**
  49600. * Gets the highest frame rate of the animation
  49601. * @returns Highest frame rate of the animation
  49602. */
  49603. Animation.prototype.getHighestFrame = function () {
  49604. var ret = 0;
  49605. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49606. if (ret < this._keys[key].frame) {
  49607. ret = this._keys[key].frame;
  49608. }
  49609. }
  49610. return ret;
  49611. };
  49612. /**
  49613. * Gets the easing function of the animation
  49614. * @returns Easing function of the animation
  49615. */
  49616. Animation.prototype.getEasingFunction = function () {
  49617. return this._easingFunction;
  49618. };
  49619. /**
  49620. * Sets the easing function of the animation
  49621. * @param easingFunction A custom mathematical formula for animation
  49622. */
  49623. Animation.prototype.setEasingFunction = function (easingFunction) {
  49624. this._easingFunction = easingFunction;
  49625. };
  49626. /**
  49627. * Interpolates a scalar linearly
  49628. * @param startValue Start value of the animation curve
  49629. * @param endValue End value of the animation curve
  49630. * @param gradient Scalar amount to interpolate
  49631. * @returns Interpolated scalar value
  49632. */
  49633. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49634. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49635. };
  49636. /**
  49637. * Interpolates a scalar cubically
  49638. * @param startValue Start value of the animation curve
  49639. * @param outTangent End tangent of the animation
  49640. * @param endValue End value of the animation curve
  49641. * @param inTangent Start tangent of the animation curve
  49642. * @param gradient Scalar amount to interpolate
  49643. * @returns Interpolated scalar value
  49644. */
  49645. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49646. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49647. };
  49648. /**
  49649. * Interpolates a quaternion using a spherical linear interpolation
  49650. * @param startValue Start value of the animation curve
  49651. * @param endValue End value of the animation curve
  49652. * @param gradient Scalar amount to interpolate
  49653. * @returns Interpolated quaternion value
  49654. */
  49655. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49656. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49657. };
  49658. /**
  49659. * Interpolates a quaternion cubically
  49660. * @param startValue Start value of the animation curve
  49661. * @param outTangent End tangent of the animation curve
  49662. * @param endValue End value of the animation curve
  49663. * @param inTangent Start tangent of the animation curve
  49664. * @param gradient Scalar amount to interpolate
  49665. * @returns Interpolated quaternion value
  49666. */
  49667. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49668. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49669. };
  49670. /**
  49671. * Interpolates a Vector3 linearl
  49672. * @param startValue Start value of the animation curve
  49673. * @param endValue End value of the animation curve
  49674. * @param gradient Scalar amount to interpolate
  49675. * @returns Interpolated scalar value
  49676. */
  49677. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49678. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49679. };
  49680. /**
  49681. * Interpolates a Vector3 cubically
  49682. * @param startValue Start value of the animation curve
  49683. * @param outTangent End tangent of the animation
  49684. * @param endValue End value of the animation curve
  49685. * @param inTangent Start tangent of the animation curve
  49686. * @param gradient Scalar amount to interpolate
  49687. * @returns InterpolatedVector3 value
  49688. */
  49689. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49690. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49691. };
  49692. /**
  49693. * Interpolates a Vector2 linearly
  49694. * @param startValue Start value of the animation curve
  49695. * @param endValue End value of the animation curve
  49696. * @param gradient Scalar amount to interpolate
  49697. * @returns Interpolated Vector2 value
  49698. */
  49699. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49700. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49701. };
  49702. /**
  49703. * Interpolates a Vector2 cubically
  49704. * @param startValue Start value of the animation curve
  49705. * @param outTangent End tangent of the animation
  49706. * @param endValue End value of the animation curve
  49707. * @param inTangent Start tangent of the animation curve
  49708. * @param gradient Scalar amount to interpolate
  49709. * @returns Interpolated Vector2 value
  49710. */
  49711. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49712. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49713. };
  49714. /**
  49715. * Interpolates a size linearly
  49716. * @param startValue Start value of the animation curve
  49717. * @param endValue End value of the animation curve
  49718. * @param gradient Scalar amount to interpolate
  49719. * @returns Interpolated Size value
  49720. */
  49721. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49722. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49723. };
  49724. /**
  49725. * Interpolates a Color3 linearly
  49726. * @param startValue Start value of the animation curve
  49727. * @param endValue End value of the animation curve
  49728. * @param gradient Scalar amount to interpolate
  49729. * @returns Interpolated Color3 value
  49730. */
  49731. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49732. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49733. };
  49734. /**
  49735. * @hidden Internal use only
  49736. */
  49737. Animation.prototype._getKeyValue = function (value) {
  49738. if (typeof value === "function") {
  49739. return value();
  49740. }
  49741. return value;
  49742. };
  49743. /**
  49744. * @hidden Internal use only
  49745. */
  49746. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49747. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49748. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49749. }
  49750. var keys = this.getKeys();
  49751. // Try to get a hash to find the right key
  49752. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  49753. if (keys[startKeyIndex].frame >= currentFrame) {
  49754. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49755. startKeyIndex--;
  49756. }
  49757. }
  49758. for (var key = startKeyIndex; key < keys.length; key++) {
  49759. var endKey = keys[key + 1];
  49760. if (endKey.frame >= currentFrame) {
  49761. var startKey = keys[key];
  49762. var startValue = this._getKeyValue(startKey.value);
  49763. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49764. return startValue;
  49765. }
  49766. var endValue = this._getKeyValue(endKey.value);
  49767. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49768. var frameDelta = endKey.frame - startKey.frame;
  49769. // gradient : percent of currentFrame between the frame inf and the frame sup
  49770. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49771. // check for easingFunction and correction of gradient
  49772. var easingFunction = this.getEasingFunction();
  49773. if (easingFunction != null) {
  49774. gradient = easingFunction.ease(gradient);
  49775. }
  49776. switch (this.dataType) {
  49777. // Float
  49778. case Animation.ANIMATIONTYPE_FLOAT:
  49779. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49780. switch (loopMode) {
  49781. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49782. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49783. return floatValue;
  49784. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49785. return offsetValue * repeatCount + floatValue;
  49786. }
  49787. break;
  49788. // Quaternion
  49789. case Animation.ANIMATIONTYPE_QUATERNION:
  49790. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49791. switch (loopMode) {
  49792. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49793. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49794. return quatValue;
  49795. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49796. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49797. }
  49798. return quatValue;
  49799. // Vector3
  49800. case Animation.ANIMATIONTYPE_VECTOR3:
  49801. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49802. switch (loopMode) {
  49803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49805. return vec3Value;
  49806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49807. return vec3Value.add(offsetValue.scale(repeatCount));
  49808. }
  49809. // Vector2
  49810. case Animation.ANIMATIONTYPE_VECTOR2:
  49811. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49812. switch (loopMode) {
  49813. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49814. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49815. return vec2Value;
  49816. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49817. return vec2Value.add(offsetValue.scale(repeatCount));
  49818. }
  49819. // Size
  49820. case Animation.ANIMATIONTYPE_SIZE:
  49821. switch (loopMode) {
  49822. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49823. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49824. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49825. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49826. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49827. }
  49828. // Color3
  49829. case Animation.ANIMATIONTYPE_COLOR3:
  49830. switch (loopMode) {
  49831. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49832. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49833. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49834. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49835. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49836. }
  49837. // Matrix
  49838. case Animation.ANIMATIONTYPE_MATRIX:
  49839. switch (loopMode) {
  49840. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49841. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49842. if (Animation.AllowMatricesInterpolation) {
  49843. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49844. }
  49845. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49846. return startValue;
  49847. }
  49848. default:
  49849. break;
  49850. }
  49851. break;
  49852. }
  49853. }
  49854. return this._getKeyValue(keys[keys.length - 1].value);
  49855. };
  49856. /**
  49857. * Defines the function to use to interpolate matrices
  49858. * @param startValue defines the start matrix
  49859. * @param endValue defines the end matrix
  49860. * @param gradient defines the gradient between both matrices
  49861. * @param result defines an optional target matrix where to store the interpolation
  49862. * @returns the interpolated matrix
  49863. */
  49864. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49865. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49866. if (result) {
  49867. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49868. return result;
  49869. }
  49870. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49871. }
  49872. if (result) {
  49873. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49874. return result;
  49875. }
  49876. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49877. };
  49878. /**
  49879. * Makes a copy of the animation
  49880. * @returns Cloned animation
  49881. */
  49882. Animation.prototype.clone = function () {
  49883. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49884. clone.enableBlending = this.enableBlending;
  49885. clone.blendingSpeed = this.blendingSpeed;
  49886. if (this._keys) {
  49887. clone.setKeys(this._keys);
  49888. }
  49889. if (this._ranges) {
  49890. clone._ranges = {};
  49891. for (var name in this._ranges) {
  49892. var range = this._ranges[name];
  49893. if (!range) {
  49894. continue;
  49895. }
  49896. clone._ranges[name] = range.clone();
  49897. }
  49898. }
  49899. return clone;
  49900. };
  49901. /**
  49902. * Sets the key frames of the animation
  49903. * @param values The animation key frames to set
  49904. */
  49905. Animation.prototype.setKeys = function (values) {
  49906. this._keys = values.slice(0);
  49907. };
  49908. /**
  49909. * Serializes the animation to an object
  49910. * @returns Serialized object
  49911. */
  49912. Animation.prototype.serialize = function () {
  49913. var serializationObject = {};
  49914. serializationObject.name = this.name;
  49915. serializationObject.property = this.targetProperty;
  49916. serializationObject.framePerSecond = this.framePerSecond;
  49917. serializationObject.dataType = this.dataType;
  49918. serializationObject.loopBehavior = this.loopMode;
  49919. serializationObject.enableBlending = this.enableBlending;
  49920. serializationObject.blendingSpeed = this.blendingSpeed;
  49921. var dataType = this.dataType;
  49922. serializationObject.keys = [];
  49923. var keys = this.getKeys();
  49924. for (var index = 0; index < keys.length; index++) {
  49925. var animationKey = keys[index];
  49926. var key = {};
  49927. key.frame = animationKey.frame;
  49928. switch (dataType) {
  49929. case Animation.ANIMATIONTYPE_FLOAT:
  49930. key.values = [animationKey.value];
  49931. break;
  49932. case Animation.ANIMATIONTYPE_QUATERNION:
  49933. case Animation.ANIMATIONTYPE_MATRIX:
  49934. case Animation.ANIMATIONTYPE_VECTOR3:
  49935. case Animation.ANIMATIONTYPE_COLOR3:
  49936. key.values = animationKey.value.asArray();
  49937. break;
  49938. }
  49939. serializationObject.keys.push(key);
  49940. }
  49941. serializationObject.ranges = [];
  49942. for (var name in this._ranges) {
  49943. var source = this._ranges[name];
  49944. if (!source) {
  49945. continue;
  49946. }
  49947. var range = {};
  49948. range.name = name;
  49949. range.from = source.from;
  49950. range.to = source.to;
  49951. serializationObject.ranges.push(range);
  49952. }
  49953. return serializationObject;
  49954. };
  49955. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49956. /**
  49957. * Get the float animation type
  49958. */
  49959. get: function () {
  49960. return Animation._ANIMATIONTYPE_FLOAT;
  49961. },
  49962. enumerable: true,
  49963. configurable: true
  49964. });
  49965. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49966. /**
  49967. * Get the Vector3 animation type
  49968. */
  49969. get: function () {
  49970. return Animation._ANIMATIONTYPE_VECTOR3;
  49971. },
  49972. enumerable: true,
  49973. configurable: true
  49974. });
  49975. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49976. /**
  49977. * Get the Vectpr2 animation type
  49978. */
  49979. get: function () {
  49980. return Animation._ANIMATIONTYPE_VECTOR2;
  49981. },
  49982. enumerable: true,
  49983. configurable: true
  49984. });
  49985. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49986. /**
  49987. * Get the Size animation type
  49988. */
  49989. get: function () {
  49990. return Animation._ANIMATIONTYPE_SIZE;
  49991. },
  49992. enumerable: true,
  49993. configurable: true
  49994. });
  49995. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49996. /**
  49997. * Get the Quaternion animation type
  49998. */
  49999. get: function () {
  50000. return Animation._ANIMATIONTYPE_QUATERNION;
  50001. },
  50002. enumerable: true,
  50003. configurable: true
  50004. });
  50005. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50006. /**
  50007. * Get the Matrix animation type
  50008. */
  50009. get: function () {
  50010. return Animation._ANIMATIONTYPE_MATRIX;
  50011. },
  50012. enumerable: true,
  50013. configurable: true
  50014. });
  50015. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50016. /**
  50017. * Get the Color3 animation type
  50018. */
  50019. get: function () {
  50020. return Animation._ANIMATIONTYPE_COLOR3;
  50021. },
  50022. enumerable: true,
  50023. configurable: true
  50024. });
  50025. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50026. /**
  50027. * Get the Relative Loop Mode
  50028. */
  50029. get: function () {
  50030. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50031. },
  50032. enumerable: true,
  50033. configurable: true
  50034. });
  50035. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50036. /**
  50037. * Get the Cycle Loop Mode
  50038. */
  50039. get: function () {
  50040. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50041. },
  50042. enumerable: true,
  50043. configurable: true
  50044. });
  50045. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50046. /**
  50047. * Get the Constant Loop Mode
  50048. */
  50049. get: function () {
  50050. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50051. },
  50052. enumerable: true,
  50053. configurable: true
  50054. });
  50055. /** @hidden */
  50056. Animation._UniversalLerp = function (left, right, amount) {
  50057. var constructor = left.constructor;
  50058. if (constructor.Lerp) { // Lerp supported
  50059. return constructor.Lerp(left, right, amount);
  50060. }
  50061. else if (constructor.Slerp) { // Slerp supported
  50062. return constructor.Slerp(left, right, amount);
  50063. }
  50064. else if (left.toFixed) { // Number
  50065. return left * (1.0 - amount) + amount * right;
  50066. }
  50067. else { // Blending not supported
  50068. return right;
  50069. }
  50070. };
  50071. /**
  50072. * Parses an animation object and creates an animation
  50073. * @param parsedAnimation Parsed animation object
  50074. * @returns Animation object
  50075. */
  50076. Animation.Parse = function (parsedAnimation) {
  50077. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50078. var dataType = parsedAnimation.dataType;
  50079. var keys = [];
  50080. var data;
  50081. var index;
  50082. if (parsedAnimation.enableBlending) {
  50083. animation.enableBlending = parsedAnimation.enableBlending;
  50084. }
  50085. if (parsedAnimation.blendingSpeed) {
  50086. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50087. }
  50088. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50089. var key = parsedAnimation.keys[index];
  50090. var inTangent;
  50091. var outTangent;
  50092. switch (dataType) {
  50093. case Animation.ANIMATIONTYPE_FLOAT:
  50094. data = key.values[0];
  50095. if (key.values.length >= 1) {
  50096. inTangent = key.values[1];
  50097. }
  50098. if (key.values.length >= 2) {
  50099. outTangent = key.values[2];
  50100. }
  50101. break;
  50102. case Animation.ANIMATIONTYPE_QUATERNION:
  50103. data = BABYLON.Quaternion.FromArray(key.values);
  50104. if (key.values.length >= 8) {
  50105. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50106. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50107. inTangent = _inTangent;
  50108. }
  50109. }
  50110. if (key.values.length >= 12) {
  50111. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50112. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50113. outTangent = _outTangent;
  50114. }
  50115. }
  50116. break;
  50117. case Animation.ANIMATIONTYPE_MATRIX:
  50118. data = BABYLON.Matrix.FromArray(key.values);
  50119. break;
  50120. case Animation.ANIMATIONTYPE_COLOR3:
  50121. data = BABYLON.Color3.FromArray(key.values);
  50122. break;
  50123. case Animation.ANIMATIONTYPE_VECTOR3:
  50124. default:
  50125. data = BABYLON.Vector3.FromArray(key.values);
  50126. break;
  50127. }
  50128. var keyData = {};
  50129. keyData.frame = key.frame;
  50130. keyData.value = data;
  50131. if (inTangent != undefined) {
  50132. keyData.inTangent = inTangent;
  50133. }
  50134. if (outTangent != undefined) {
  50135. keyData.outTangent = outTangent;
  50136. }
  50137. keys.push(keyData);
  50138. }
  50139. animation.setKeys(keys);
  50140. if (parsedAnimation.ranges) {
  50141. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50142. data = parsedAnimation.ranges[index];
  50143. animation.createRange(data.name, data.from, data.to);
  50144. }
  50145. }
  50146. return animation;
  50147. };
  50148. /**
  50149. * Appends the serialized animations from the source animations
  50150. * @param source Source containing the animations
  50151. * @param destination Target to store the animations
  50152. */
  50153. Animation.AppendSerializedAnimations = function (source, destination) {
  50154. if (source.animations) {
  50155. destination.animations = [];
  50156. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50157. var animation = source.animations[animationIndex];
  50158. destination.animations.push(animation.serialize());
  50159. }
  50160. }
  50161. };
  50162. /**
  50163. * Use matrix interpolation instead of using direct key value when animating matrices
  50164. */
  50165. Animation.AllowMatricesInterpolation = false;
  50166. /**
  50167. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50168. */
  50169. Animation.AllowMatrixDecomposeForInterpolation = true;
  50170. // Statics
  50171. /**
  50172. * Float animation type
  50173. */
  50174. Animation._ANIMATIONTYPE_FLOAT = 0;
  50175. /**
  50176. * Vector3 animation type
  50177. */
  50178. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50179. /**
  50180. * Quaternion animation type
  50181. */
  50182. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50183. /**
  50184. * Matrix animation type
  50185. */
  50186. Animation._ANIMATIONTYPE_MATRIX = 3;
  50187. /**
  50188. * Color3 animation type
  50189. */
  50190. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50191. /**
  50192. * Vector2 animation type
  50193. */
  50194. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50195. /**
  50196. * Size animation type
  50197. */
  50198. Animation._ANIMATIONTYPE_SIZE = 6;
  50199. /**
  50200. * Relative Loop Mode
  50201. */
  50202. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50203. /**
  50204. * Cycle Loop Mode
  50205. */
  50206. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50207. /**
  50208. * Constant Loop Mode
  50209. */
  50210. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50211. return Animation;
  50212. }());
  50213. BABYLON.Animation = Animation;
  50214. })(BABYLON || (BABYLON = {}));
  50215. //# sourceMappingURL=babylon.animation.js.map
  50216. var BABYLON;
  50217. (function (BABYLON) {
  50218. /**
  50219. * This class defines the direct association between an animation and a target
  50220. */
  50221. var TargetedAnimation = /** @class */ (function () {
  50222. function TargetedAnimation() {
  50223. }
  50224. return TargetedAnimation;
  50225. }());
  50226. BABYLON.TargetedAnimation = TargetedAnimation;
  50227. /**
  50228. * Use this class to create coordinated animations on multiple targets
  50229. */
  50230. var AnimationGroup = /** @class */ (function () {
  50231. function AnimationGroup(name, scene) {
  50232. if (scene === void 0) { scene = null; }
  50233. this.name = name;
  50234. this._targetedAnimations = new Array();
  50235. this._animatables = new Array();
  50236. this._from = Number.MAX_VALUE;
  50237. this._to = -Number.MAX_VALUE;
  50238. this._speedRatio = 1;
  50239. this.onAnimationEndObservable = new BABYLON.Observable();
  50240. /**
  50241. * This observable will notify when all animations have ended.
  50242. */
  50243. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50244. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50245. this._scene.animationGroups.push(this);
  50246. }
  50247. Object.defineProperty(AnimationGroup.prototype, "from", {
  50248. /**
  50249. * Gets the first frame
  50250. */
  50251. get: function () {
  50252. return this._from;
  50253. },
  50254. enumerable: true,
  50255. configurable: true
  50256. });
  50257. Object.defineProperty(AnimationGroup.prototype, "to", {
  50258. /**
  50259. * Gets the last frame
  50260. */
  50261. get: function () {
  50262. return this._to;
  50263. },
  50264. enumerable: true,
  50265. configurable: true
  50266. });
  50267. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50268. /**
  50269. * Define if the animations are started
  50270. */
  50271. get: function () {
  50272. return this._isStarted;
  50273. },
  50274. enumerable: true,
  50275. configurable: true
  50276. });
  50277. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50278. /**
  50279. * Gets or sets the speed ratio to use for all animations
  50280. */
  50281. get: function () {
  50282. return this._speedRatio;
  50283. },
  50284. /**
  50285. * Gets or sets the speed ratio to use for all animations
  50286. */
  50287. set: function (value) {
  50288. if (this._speedRatio === value) {
  50289. return;
  50290. }
  50291. this._speedRatio = value;
  50292. for (var index = 0; index < this._animatables.length; index++) {
  50293. var animatable = this._animatables[index];
  50294. animatable.speedRatio = this._speedRatio;
  50295. }
  50296. },
  50297. enumerable: true,
  50298. configurable: true
  50299. });
  50300. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50301. /**
  50302. * Gets the targeted animations for this animation group
  50303. */
  50304. get: function () {
  50305. return this._targetedAnimations;
  50306. },
  50307. enumerable: true,
  50308. configurable: true
  50309. });
  50310. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50311. /**
  50312. * returning the list of animatables controlled by this animation group.
  50313. */
  50314. get: function () {
  50315. return this._animatables;
  50316. },
  50317. enumerable: true,
  50318. configurable: true
  50319. });
  50320. /**
  50321. * Add an animation (with its target) in the group
  50322. * @param animation defines the animation we want to add
  50323. * @param target defines the target of the animation
  50324. * @returns the {BABYLON.TargetedAnimation} object
  50325. */
  50326. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50327. var targetedAnimation = {
  50328. animation: animation,
  50329. target: target
  50330. };
  50331. var keys = animation.getKeys();
  50332. if (this._from > keys[0].frame) {
  50333. this._from = keys[0].frame;
  50334. }
  50335. if (this._to < keys[keys.length - 1].frame) {
  50336. this._to = keys[keys.length - 1].frame;
  50337. }
  50338. this._targetedAnimations.push(targetedAnimation);
  50339. return targetedAnimation;
  50340. };
  50341. /**
  50342. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50343. * It can add constant keys at begin or end
  50344. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50345. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50346. */
  50347. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50348. if (beginFrame === void 0) { beginFrame = null; }
  50349. if (endFrame === void 0) { endFrame = null; }
  50350. if (beginFrame == null)
  50351. beginFrame = this._from;
  50352. if (endFrame == null)
  50353. endFrame = this._to;
  50354. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50355. var targetedAnimation = this._targetedAnimations[index];
  50356. var keys = targetedAnimation.animation.getKeys();
  50357. var startKey = keys[0];
  50358. var endKey = keys[keys.length - 1];
  50359. if (startKey.frame > beginFrame) {
  50360. var newKey = {
  50361. frame: beginFrame,
  50362. value: startKey.value,
  50363. inTangent: startKey.inTangent,
  50364. outTangent: startKey.outTangent,
  50365. interpolation: startKey.interpolation
  50366. };
  50367. keys.splice(0, 0, newKey);
  50368. }
  50369. if (endKey.frame < endFrame) {
  50370. var newKey = {
  50371. frame: endFrame,
  50372. value: endKey.value,
  50373. inTangent: endKey.outTangent,
  50374. outTangent: endKey.outTangent,
  50375. interpolation: endKey.interpolation
  50376. };
  50377. keys.push(newKey);
  50378. }
  50379. }
  50380. this._from = beginFrame;
  50381. this._to = endFrame;
  50382. return this;
  50383. };
  50384. /**
  50385. * Start all animations on given targets
  50386. * @param loop defines if animations must loop
  50387. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50388. * @param from defines the from key (optional)
  50389. * @param to defines the to key (optional)
  50390. * @returns the current animation group
  50391. */
  50392. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50393. var _this = this;
  50394. if (loop === void 0) { loop = false; }
  50395. if (speedRatio === void 0) { speedRatio = 1; }
  50396. if (this._isStarted || this._targetedAnimations.length === 0) {
  50397. return this;
  50398. }
  50399. var _loop_1 = function (targetedAnimation) {
  50400. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50401. animatable.onAnimationEnd = function () {
  50402. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50403. _this._checkAnimationGroupEnded(animatable);
  50404. };
  50405. this_1._animatables.push(animatable);
  50406. };
  50407. var this_1 = this;
  50408. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50409. var targetedAnimation = _a[_i];
  50410. _loop_1(targetedAnimation);
  50411. }
  50412. this._speedRatio = speedRatio;
  50413. this._isStarted = true;
  50414. return this;
  50415. };
  50416. /**
  50417. * Pause all animations
  50418. */
  50419. AnimationGroup.prototype.pause = function () {
  50420. if (!this._isStarted) {
  50421. return this;
  50422. }
  50423. for (var index = 0; index < this._animatables.length; index++) {
  50424. var animatable = this._animatables[index];
  50425. animatable.pause();
  50426. }
  50427. return this;
  50428. };
  50429. /**
  50430. * Play all animations to initial state
  50431. * This function will start() the animations if they were not started or will restart() them if they were paused
  50432. * @param loop defines if animations must loop
  50433. */
  50434. AnimationGroup.prototype.play = function (loop) {
  50435. // only if all animatables are ready and exist
  50436. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50437. if (loop !== undefined) {
  50438. for (var index = 0; index < this._animatables.length; index++) {
  50439. var animatable = this._animatables[index];
  50440. animatable.loopAnimation = loop;
  50441. }
  50442. }
  50443. this.restart();
  50444. }
  50445. else {
  50446. this.stop();
  50447. this.start(loop, this._speedRatio);
  50448. }
  50449. return this;
  50450. };
  50451. /**
  50452. * Reset all animations to initial state
  50453. */
  50454. AnimationGroup.prototype.reset = function () {
  50455. if (!this._isStarted) {
  50456. return this;
  50457. }
  50458. for (var index = 0; index < this._animatables.length; index++) {
  50459. var animatable = this._animatables[index];
  50460. animatable.reset();
  50461. }
  50462. return this;
  50463. };
  50464. /**
  50465. * Restart animations from key 0
  50466. */
  50467. AnimationGroup.prototype.restart = function () {
  50468. if (!this._isStarted) {
  50469. return this;
  50470. }
  50471. for (var index = 0; index < this._animatables.length; index++) {
  50472. var animatable = this._animatables[index];
  50473. animatable.restart();
  50474. }
  50475. return this;
  50476. };
  50477. /**
  50478. * Stop all animations
  50479. */
  50480. AnimationGroup.prototype.stop = function () {
  50481. if (!this._isStarted) {
  50482. return this;
  50483. }
  50484. var list = this._animatables.slice();
  50485. for (var index = 0; index < list.length; index++) {
  50486. list[index].stop();
  50487. }
  50488. this._isStarted = false;
  50489. return this;
  50490. };
  50491. /**
  50492. * Set animation weight for all animatables
  50493. * @param weight defines the weight to use
  50494. * @return the animationGroup
  50495. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50496. */
  50497. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50498. for (var index = 0; index < this._animatables.length; index++) {
  50499. var animatable = this._animatables[index];
  50500. animatable.weight = weight;
  50501. }
  50502. return this;
  50503. };
  50504. /**
  50505. * Synchronize and normalize all animatables with a source animatable
  50506. * @param root defines the root animatable to synchronize with
  50507. * @return the animationGroup
  50508. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50509. */
  50510. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50511. for (var index = 0; index < this._animatables.length; index++) {
  50512. var animatable = this._animatables[index];
  50513. animatable.syncWith(root);
  50514. }
  50515. return this;
  50516. };
  50517. /**
  50518. * Goes to a specific frame in this animation group
  50519. * @param frame the frame number to go to
  50520. * @return the animationGroup
  50521. */
  50522. AnimationGroup.prototype.goToFrame = function (frame) {
  50523. if (!this._isStarted) {
  50524. return this;
  50525. }
  50526. for (var index = 0; index < this._animatables.length; index++) {
  50527. var animatable = this._animatables[index];
  50528. animatable.goToFrame(frame);
  50529. }
  50530. return this;
  50531. };
  50532. /**
  50533. * Dispose all associated resources
  50534. */
  50535. AnimationGroup.prototype.dispose = function () {
  50536. this._targetedAnimations = [];
  50537. this._animatables = [];
  50538. var index = this._scene.animationGroups.indexOf(this);
  50539. if (index > -1) {
  50540. this._scene.animationGroups.splice(index, 1);
  50541. }
  50542. };
  50543. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50544. // animatable should be taken out of the array
  50545. var idx = this._animatables.indexOf(animatable);
  50546. if (idx > -1) {
  50547. this._animatables.splice(idx, 1);
  50548. }
  50549. // all animatables were removed? animation group ended!
  50550. if (this._animatables.length === 0) {
  50551. this._isStarted = false;
  50552. this.onAnimationGroupEndObservable.notifyObservers(this);
  50553. }
  50554. };
  50555. return AnimationGroup;
  50556. }());
  50557. BABYLON.AnimationGroup = AnimationGroup;
  50558. })(BABYLON || (BABYLON = {}));
  50559. //# sourceMappingURL=babylon.animationGroup.js.map
  50560. var BABYLON;
  50561. (function (BABYLON) {
  50562. /**
  50563. * Defines a runtime animation
  50564. */
  50565. var RuntimeAnimation = /** @class */ (function () {
  50566. /**
  50567. * Create a new RuntimeAnimation object
  50568. * @param target defines the target of the animation
  50569. * @param animation defines the source animation object
  50570. * @param scene defines the hosting scene
  50571. * @param host defines the initiating Animatable
  50572. */
  50573. function RuntimeAnimation(target, animation, scene, host) {
  50574. var _this = this;
  50575. this._events = new Array();
  50576. /**
  50577. * The current frame of the runtime animation
  50578. */
  50579. this._currentFrame = 0;
  50580. /**
  50581. * The original value of the runtime animation
  50582. */
  50583. this._originalValue = new Array();
  50584. /**
  50585. * The offsets cache of the runtime animation
  50586. */
  50587. this._offsetsCache = {};
  50588. /**
  50589. * The high limits cache of the runtime animation
  50590. */
  50591. this._highLimitsCache = {};
  50592. /**
  50593. * Specifies if the runtime animation has been stopped
  50594. */
  50595. this._stopped = false;
  50596. /**
  50597. * The blending factor of the runtime animation
  50598. */
  50599. this._blendingFactor = 0;
  50600. /**
  50601. * The target path of the runtime animation
  50602. */
  50603. this._targetPath = "";
  50604. /**
  50605. * The weight of the runtime animation
  50606. */
  50607. this._weight = 1.0;
  50608. /**
  50609. * The ratio offset of the runtime animation
  50610. */
  50611. this._ratioOffset = 0;
  50612. /**
  50613. * The previous delay of the runtime animation
  50614. */
  50615. this._previousDelay = 0;
  50616. /**
  50617. * The previous ratio of the runtime animation
  50618. */
  50619. this._previousRatio = 0;
  50620. this._animation = animation;
  50621. this._target = target;
  50622. this._scene = scene;
  50623. this._host = host;
  50624. animation._runtimeAnimations.push(this);
  50625. // Cloning events locally
  50626. var events = animation.getEvents();
  50627. if (events && events.length > 0) {
  50628. events.forEach(function (e) {
  50629. _this._events.push(e._clone());
  50630. });
  50631. }
  50632. }
  50633. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50634. /**
  50635. * Gets the current frame of the runtime animation
  50636. */
  50637. get: function () {
  50638. return this._currentFrame;
  50639. },
  50640. enumerable: true,
  50641. configurable: true
  50642. });
  50643. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50644. /**
  50645. * Gets the weight of the runtime animation
  50646. */
  50647. get: function () {
  50648. return this._weight;
  50649. },
  50650. enumerable: true,
  50651. configurable: true
  50652. });
  50653. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50654. /**
  50655. * Gets the current value of the runtime animation
  50656. */
  50657. get: function () {
  50658. return this._currentValue;
  50659. },
  50660. enumerable: true,
  50661. configurable: true
  50662. });
  50663. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50664. /**
  50665. * Gets the target path of the runtime animation
  50666. */
  50667. get: function () {
  50668. return this._targetPath;
  50669. },
  50670. enumerable: true,
  50671. configurable: true
  50672. });
  50673. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50674. /**
  50675. * Gets the actual target of the runtime animation
  50676. */
  50677. get: function () {
  50678. return this._activeTarget;
  50679. },
  50680. enumerable: true,
  50681. configurable: true
  50682. });
  50683. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50684. /**
  50685. * Gets the animation from the runtime animation
  50686. */
  50687. get: function () {
  50688. return this._animation;
  50689. },
  50690. enumerable: true,
  50691. configurable: true
  50692. });
  50693. /**
  50694. * Resets the runtime animation to the beginning
  50695. * @param restoreOriginal defines whether to restore the target property to the original value
  50696. */
  50697. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50698. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50699. if (restoreOriginal) {
  50700. if (this._target instanceof Array) {
  50701. var index = 0;
  50702. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50703. var target = _a[_i];
  50704. if (this._originalValue[index] !== undefined) {
  50705. this._setValue(target, this._originalValue[index], -1);
  50706. }
  50707. index++;
  50708. }
  50709. }
  50710. else {
  50711. if (this._originalValue[0] !== undefined) {
  50712. this._setValue(this._target, this._originalValue[0], -1);
  50713. }
  50714. }
  50715. }
  50716. this._offsetsCache = {};
  50717. this._highLimitsCache = {};
  50718. this._currentFrame = 0;
  50719. this._blendingFactor = 0;
  50720. this._originalValue = new Array();
  50721. // Events
  50722. for (var index = 0; index < this._events.length; index++) {
  50723. this._events[index].isDone = false;
  50724. }
  50725. };
  50726. /**
  50727. * Specifies if the runtime animation is stopped
  50728. * @returns Boolean specifying if the runtime animation is stopped
  50729. */
  50730. RuntimeAnimation.prototype.isStopped = function () {
  50731. return this._stopped;
  50732. };
  50733. /**
  50734. * Disposes of the runtime animation
  50735. */
  50736. RuntimeAnimation.prototype.dispose = function () {
  50737. var index = this._animation.runtimeAnimations.indexOf(this);
  50738. if (index > -1) {
  50739. this._animation.runtimeAnimations.splice(index, 1);
  50740. }
  50741. };
  50742. /**
  50743. * Interpolates the animation from the current frame
  50744. * @param currentFrame The frame to interpolate the animation to
  50745. * @param repeatCount The number of times that the animation should loop
  50746. * @param loopMode The type of looping mode to use
  50747. * @param offsetValue Animation offset value
  50748. * @param highLimitValue The high limit value
  50749. * @returns The interpolated value
  50750. */
  50751. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50752. this._currentFrame = currentFrame;
  50753. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50754. this._workValue = BABYLON.Matrix.Zero();
  50755. }
  50756. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50757. };
  50758. /**
  50759. * Apply the interpolated value to the target
  50760. * @param currentValue defines the value computed by the animation
  50761. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50762. */
  50763. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50764. if (weight === void 0) { weight = 1.0; }
  50765. if (this._target instanceof Array) {
  50766. var index = 0;
  50767. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50768. var target = _a[_i];
  50769. this._setValue(target, currentValue, weight, index);
  50770. index++;
  50771. }
  50772. }
  50773. else {
  50774. this._setValue(this._target, currentValue, weight);
  50775. }
  50776. };
  50777. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50778. if (targetIndex === void 0) { targetIndex = 0; }
  50779. // Set value
  50780. var path;
  50781. var destination;
  50782. var targetPropertyPath = this._animation.targetPropertyPath;
  50783. if (targetPropertyPath.length > 1) {
  50784. var property = target[targetPropertyPath[0]];
  50785. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50786. property = property[targetPropertyPath[index]];
  50787. }
  50788. path = targetPropertyPath[targetPropertyPath.length - 1];
  50789. destination = property;
  50790. }
  50791. else {
  50792. path = targetPropertyPath[0];
  50793. destination = target;
  50794. }
  50795. this._targetPath = path;
  50796. this._activeTarget = destination;
  50797. this._weight = weight;
  50798. if (this._originalValue[targetIndex] === undefined) {
  50799. var originalValue = void 0;
  50800. if (destination.getRestPose && path === "_matrix") { // For bones
  50801. originalValue = destination.getRestPose();
  50802. }
  50803. else {
  50804. originalValue = destination[path];
  50805. }
  50806. if (originalValue && originalValue.clone) {
  50807. this._originalValue[targetIndex] = originalValue.clone();
  50808. }
  50809. else {
  50810. this._originalValue[targetIndex] = originalValue;
  50811. }
  50812. }
  50813. // Blending
  50814. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50815. if (enableBlending && this._blendingFactor <= 1.0) {
  50816. if (!this._originalBlendValue) {
  50817. var originalValue = destination[path];
  50818. if (originalValue.clone) {
  50819. this._originalBlendValue = originalValue.clone();
  50820. }
  50821. else {
  50822. this._originalBlendValue = originalValue;
  50823. }
  50824. }
  50825. if (this._originalBlendValue.m) { // Matrix
  50826. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50827. if (this._currentValue) {
  50828. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50829. }
  50830. else {
  50831. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50832. }
  50833. }
  50834. else {
  50835. if (this._currentValue) {
  50836. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50837. }
  50838. else {
  50839. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50840. }
  50841. }
  50842. }
  50843. else {
  50844. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50845. }
  50846. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50847. this._blendingFactor += blendingSpeed;
  50848. }
  50849. else {
  50850. this._currentValue = currentValue;
  50851. }
  50852. if (weight !== -1.0) {
  50853. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50854. }
  50855. else {
  50856. destination[path] = this._currentValue;
  50857. }
  50858. if (target.markAsDirty) {
  50859. target.markAsDirty(this._animation.targetProperty);
  50860. }
  50861. };
  50862. /**
  50863. * Gets the loop pmode of the runtime animation
  50864. * @returns Loop Mode
  50865. */
  50866. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50867. if (this._target && this._target.animationPropertiesOverride) {
  50868. return this._target.animationPropertiesOverride.loopMode;
  50869. }
  50870. return this._animation.loopMode;
  50871. };
  50872. /**
  50873. * Move the current animation to a given frame
  50874. * @param frame defines the frame to move to
  50875. */
  50876. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50877. var keys = this._animation.getKeys();
  50878. if (frame < keys[0].frame) {
  50879. frame = keys[0].frame;
  50880. }
  50881. else if (frame > keys[keys.length - 1].frame) {
  50882. frame = keys[keys.length - 1].frame;
  50883. }
  50884. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50885. this.setValue(currentValue, -1);
  50886. };
  50887. /**
  50888. * @hidden Internal use only
  50889. */
  50890. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50891. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50892. this._ratioOffset = this._previousRatio - newRatio;
  50893. };
  50894. /**
  50895. * Execute the current animation
  50896. * @param delay defines the delay to add to the current frame
  50897. * @param from defines the lower bound of the animation range
  50898. * @param to defines the upper bound of the animation range
  50899. * @param loop defines if the current animation must loop
  50900. * @param speedRatio defines the current speed ratio
  50901. * @param weight defines the weight of the animation (default is -1 so no weight)
  50902. * @returns a boolean indicating if the animation is running
  50903. */
  50904. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50905. if (weight === void 0) { weight = -1.0; }
  50906. var targetPropertyPath = this._animation.targetPropertyPath;
  50907. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50908. this._stopped = true;
  50909. return false;
  50910. }
  50911. var returnValue = true;
  50912. var keys = this._animation.getKeys();
  50913. // Adding a start key at frame 0 if missing
  50914. if (keys[0].frame !== 0) {
  50915. var newKey = { frame: 0, value: keys[0].value };
  50916. keys.splice(0, 0, newKey);
  50917. }
  50918. // Adding a duplicate key when there is only one key at frame zero
  50919. else if (keys.length === 1) {
  50920. var newKey = { frame: 0.001, value: keys[0].value };
  50921. keys.push(newKey);
  50922. }
  50923. // Check limits
  50924. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50925. from = keys[0].frame;
  50926. }
  50927. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50928. to = keys[keys.length - 1].frame;
  50929. }
  50930. //to and from cannot be the same key
  50931. if (from === to) {
  50932. if (from > keys[0].frame) {
  50933. from--;
  50934. }
  50935. else if (to < keys[keys.length - 1].frame) {
  50936. to++;
  50937. }
  50938. }
  50939. // Compute ratio
  50940. var range = to - from;
  50941. var offsetValue;
  50942. // ratio represents the frame delta between from and to
  50943. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50944. var highLimitValue = 0;
  50945. this._previousDelay = delay;
  50946. this._previousRatio = ratio;
  50947. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50948. returnValue = false;
  50949. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50950. }
  50951. else {
  50952. // Get max value if required
  50953. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50954. var keyOffset = to.toString() + from.toString();
  50955. if (!this._offsetsCache[keyOffset]) {
  50956. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50957. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50958. switch (this._animation.dataType) {
  50959. // Float
  50960. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50961. this._offsetsCache[keyOffset] = toValue - fromValue;
  50962. break;
  50963. // Quaternion
  50964. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50965. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50966. break;
  50967. // Vector3
  50968. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50969. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50970. // Vector2
  50971. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50972. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50973. // Size
  50974. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50975. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50976. // Color3
  50977. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50978. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50979. default:
  50980. break;
  50981. }
  50982. this._highLimitsCache[keyOffset] = toValue;
  50983. }
  50984. highLimitValue = this._highLimitsCache[keyOffset];
  50985. offsetValue = this._offsetsCache[keyOffset];
  50986. }
  50987. }
  50988. if (offsetValue === undefined) {
  50989. switch (this._animation.dataType) {
  50990. // Float
  50991. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50992. offsetValue = 0;
  50993. break;
  50994. // Quaternion
  50995. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50996. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50997. break;
  50998. // Vector3
  50999. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51000. offsetValue = BABYLON.Vector3.Zero();
  51001. break;
  51002. // Vector2
  51003. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51004. offsetValue = BABYLON.Vector2.Zero();
  51005. break;
  51006. // Size
  51007. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51008. offsetValue = BABYLON.Size.Zero();
  51009. break;
  51010. // Color3
  51011. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51012. offsetValue = BABYLON.Color3.Black();
  51013. }
  51014. }
  51015. // Compute value
  51016. var repeatCount = (ratio / range) >> 0;
  51017. var currentFrame = returnValue ? from + ratio % range : to;
  51018. // Need to normalize?
  51019. if (this._host && this._host.syncRoot) {
  51020. var syncRoot = this._host.syncRoot;
  51021. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51022. currentFrame = from + (to - from) * hostNormalizedFrame;
  51023. }
  51024. // Reset events if looping
  51025. var events = this._events;
  51026. if (range > 0 && this.currentFrame > currentFrame ||
  51027. range < 0 && this.currentFrame < currentFrame) {
  51028. // Need to reset animation events
  51029. for (var index = 0; index < events.length; index++) {
  51030. if (!events[index].onlyOnce) {
  51031. // reset event, the animation is looping
  51032. events[index].isDone = false;
  51033. }
  51034. }
  51035. }
  51036. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51037. // Set value
  51038. this.setValue(currentValue, weight);
  51039. // Check events
  51040. for (var index = 0; index < events.length; index++) {
  51041. // Make sure current frame has passed event frame and that event frame is within the current range
  51042. // Also, handle both forward and reverse animations
  51043. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51044. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51045. var event = events[index];
  51046. if (!event.isDone) {
  51047. // If event should be done only once, remove it.
  51048. if (event.onlyOnce) {
  51049. events.splice(index, 1);
  51050. index--;
  51051. }
  51052. event.isDone = true;
  51053. event.action();
  51054. } // Don't do anything if the event has already be done.
  51055. }
  51056. }
  51057. if (!returnValue) {
  51058. this._stopped = true;
  51059. }
  51060. return returnValue;
  51061. };
  51062. return RuntimeAnimation;
  51063. }());
  51064. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51065. })(BABYLON || (BABYLON = {}));
  51066. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51067. var BABYLON;
  51068. (function (BABYLON) {
  51069. /**
  51070. * Class used to store an actual running animation
  51071. */
  51072. var Animatable = /** @class */ (function () {
  51073. /**
  51074. * Creates a new Animatable
  51075. * @param scene defines the hosting scene
  51076. * @param target defines the target object
  51077. * @param fromFrame defines the starting frame number (default is 0)
  51078. * @param toFrame defines the ending frame number (default is 100)
  51079. * @param loopAnimation defines if the animation must loop (default is false)
  51080. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51081. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51082. * @param animations defines a group of animation to add to the new Animatable
  51083. */
  51084. function Animatable(scene,
  51085. /** defines the target object */
  51086. target,
  51087. /** defines the starting frame number (default is 0) */
  51088. fromFrame,
  51089. /** defines the ending frame number (default is 100) */
  51090. toFrame,
  51091. /** defines if the animation must loop (default is false) */
  51092. loopAnimation, speedRatio,
  51093. /** defines a callback to call when animation ends if it is not looping */
  51094. onAnimationEnd, animations) {
  51095. if (fromFrame === void 0) { fromFrame = 0; }
  51096. if (toFrame === void 0) { toFrame = 100; }
  51097. if (loopAnimation === void 0) { loopAnimation = false; }
  51098. if (speedRatio === void 0) { speedRatio = 1.0; }
  51099. this.target = target;
  51100. this.fromFrame = fromFrame;
  51101. this.toFrame = toFrame;
  51102. this.loopAnimation = loopAnimation;
  51103. this.onAnimationEnd = onAnimationEnd;
  51104. this._localDelayOffset = null;
  51105. this._pausedDelay = null;
  51106. this._runtimeAnimations = new Array();
  51107. this._paused = false;
  51108. this._speedRatio = 1;
  51109. this._weight = -1.0;
  51110. /**
  51111. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51112. * This will only apply for non looping animation (default is true)
  51113. */
  51114. this.disposeOnEnd = true;
  51115. /**
  51116. * Gets a boolean indicating if the animation has started
  51117. */
  51118. this.animationStarted = false;
  51119. /**
  51120. * Observer raised when the animation ends
  51121. */
  51122. this.onAnimationEndObservable = new BABYLON.Observable();
  51123. this._scene = scene;
  51124. if (animations) {
  51125. this.appendAnimations(target, animations);
  51126. }
  51127. this._speedRatio = speedRatio;
  51128. scene._activeAnimatables.push(this);
  51129. }
  51130. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51131. /**
  51132. * Gets the root Animatable used to synchronize and normalize animations
  51133. */
  51134. get: function () {
  51135. return this._syncRoot;
  51136. },
  51137. enumerable: true,
  51138. configurable: true
  51139. });
  51140. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51141. /**
  51142. * Gets the current frame of the first RuntimeAnimation
  51143. * Used to synchronize Animatables
  51144. */
  51145. get: function () {
  51146. if (this._runtimeAnimations.length === 0) {
  51147. return 0;
  51148. }
  51149. return this._runtimeAnimations[0].currentFrame;
  51150. },
  51151. enumerable: true,
  51152. configurable: true
  51153. });
  51154. Object.defineProperty(Animatable.prototype, "weight", {
  51155. /**
  51156. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51157. */
  51158. get: function () {
  51159. return this._weight;
  51160. },
  51161. set: function (value) {
  51162. if (value === -1) { // -1 is ok and means no weight
  51163. this._weight = -1;
  51164. return;
  51165. }
  51166. // Else weight must be in [0, 1] range
  51167. this._weight = Math.min(Math.max(value, 0), 1.0);
  51168. },
  51169. enumerable: true,
  51170. configurable: true
  51171. });
  51172. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51173. /**
  51174. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51175. */
  51176. get: function () {
  51177. return this._speedRatio;
  51178. },
  51179. set: function (value) {
  51180. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51181. var animation = this._runtimeAnimations[index];
  51182. animation._prepareForSpeedRatioChange(value);
  51183. }
  51184. this._speedRatio = value;
  51185. },
  51186. enumerable: true,
  51187. configurable: true
  51188. });
  51189. // Methods
  51190. /**
  51191. * Synchronize and normalize current Animatable with a source Animatable
  51192. * This is useful when using animation weights and when animations are not of the same length
  51193. * @param root defines the root Animatable to synchronize with
  51194. * @returns the current Animatable
  51195. */
  51196. Animatable.prototype.syncWith = function (root) {
  51197. this._syncRoot = root;
  51198. if (root) {
  51199. // Make sure this animatable will animate after the root
  51200. var index = this._scene._activeAnimatables.indexOf(this);
  51201. if (index > -1) {
  51202. this._scene._activeAnimatables.splice(index, 1);
  51203. this._scene._activeAnimatables.push(this);
  51204. }
  51205. }
  51206. return this;
  51207. };
  51208. /**
  51209. * Gets the list of runtime animations
  51210. * @returns an array of RuntimeAnimation
  51211. */
  51212. Animatable.prototype.getAnimations = function () {
  51213. return this._runtimeAnimations;
  51214. };
  51215. /**
  51216. * Adds more animations to the current animatable
  51217. * @param target defines the target of the animations
  51218. * @param animations defines the new animations to add
  51219. */
  51220. Animatable.prototype.appendAnimations = function (target, animations) {
  51221. for (var index = 0; index < animations.length; index++) {
  51222. var animation = animations[index];
  51223. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51224. }
  51225. };
  51226. /**
  51227. * Gets the source animation for a specific property
  51228. * @param property defines the propertyu to look for
  51229. * @returns null or the source animation for the given property
  51230. */
  51231. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51232. var runtimeAnimations = this._runtimeAnimations;
  51233. for (var index = 0; index < runtimeAnimations.length; index++) {
  51234. if (runtimeAnimations[index].animation.targetProperty === property) {
  51235. return runtimeAnimations[index].animation;
  51236. }
  51237. }
  51238. return null;
  51239. };
  51240. /**
  51241. * Gets the runtime animation for a specific property
  51242. * @param property defines the propertyu to look for
  51243. * @returns null or the runtime animation for the given property
  51244. */
  51245. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51246. var runtimeAnimations = this._runtimeAnimations;
  51247. for (var index = 0; index < runtimeAnimations.length; index++) {
  51248. if (runtimeAnimations[index].animation.targetProperty === property) {
  51249. return runtimeAnimations[index];
  51250. }
  51251. }
  51252. return null;
  51253. };
  51254. /**
  51255. * Resets the animatable to its original state
  51256. */
  51257. Animatable.prototype.reset = function () {
  51258. var runtimeAnimations = this._runtimeAnimations;
  51259. for (var index = 0; index < runtimeAnimations.length; index++) {
  51260. runtimeAnimations[index].reset(true);
  51261. }
  51262. this._localDelayOffset = null;
  51263. this._pausedDelay = null;
  51264. };
  51265. /**
  51266. * Allows the animatable to blend with current running animations
  51267. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51268. * @param blendingSpeed defines the blending speed to use
  51269. */
  51270. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51271. var runtimeAnimations = this._runtimeAnimations;
  51272. for (var index = 0; index < runtimeAnimations.length; index++) {
  51273. runtimeAnimations[index].animation.enableBlending = true;
  51274. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51275. }
  51276. };
  51277. /**
  51278. * Disable animation blending
  51279. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51280. */
  51281. Animatable.prototype.disableBlending = function () {
  51282. var runtimeAnimations = this._runtimeAnimations;
  51283. for (var index = 0; index < runtimeAnimations.length; index++) {
  51284. runtimeAnimations[index].animation.enableBlending = false;
  51285. }
  51286. };
  51287. /**
  51288. * Jump directly to a given frame
  51289. * @param frame defines the frame to jump to
  51290. */
  51291. Animatable.prototype.goToFrame = function (frame) {
  51292. var runtimeAnimations = this._runtimeAnimations;
  51293. if (runtimeAnimations[0]) {
  51294. var fps = runtimeAnimations[0].animation.framePerSecond;
  51295. var currentFrame = runtimeAnimations[0].currentFrame;
  51296. var adjustTime = frame - currentFrame;
  51297. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51298. if (this._localDelayOffset === null) {
  51299. this._localDelayOffset = 0;
  51300. }
  51301. this._localDelayOffset -= delay;
  51302. }
  51303. for (var index = 0; index < runtimeAnimations.length; index++) {
  51304. runtimeAnimations[index].goToFrame(frame);
  51305. }
  51306. };
  51307. /**
  51308. * Pause the animation
  51309. */
  51310. Animatable.prototype.pause = function () {
  51311. if (this._paused) {
  51312. return;
  51313. }
  51314. this._paused = true;
  51315. };
  51316. /**
  51317. * Restart the animation
  51318. */
  51319. Animatable.prototype.restart = function () {
  51320. this._paused = false;
  51321. };
  51322. Animatable.prototype._raiseOnAnimationEnd = function () {
  51323. if (this.onAnimationEnd) {
  51324. this.onAnimationEnd();
  51325. }
  51326. this.onAnimationEndObservable.notifyObservers(this);
  51327. };
  51328. /**
  51329. * Stop and delete the current animation
  51330. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51331. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  51332. */
  51333. Animatable.prototype.stop = function (animationName, targetMask) {
  51334. if (animationName || targetMask) {
  51335. var idx = this._scene._activeAnimatables.indexOf(this);
  51336. if (idx > -1) {
  51337. var runtimeAnimations = this._runtimeAnimations;
  51338. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51339. var runtimeAnimation = runtimeAnimations[index];
  51340. if (animationName && runtimeAnimation.animation.name != animationName) {
  51341. continue;
  51342. }
  51343. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51344. continue;
  51345. }
  51346. runtimeAnimation.dispose();
  51347. runtimeAnimations.splice(index, 1);
  51348. }
  51349. if (runtimeAnimations.length == 0) {
  51350. this._scene._activeAnimatables.splice(idx, 1);
  51351. this._raiseOnAnimationEnd();
  51352. }
  51353. }
  51354. }
  51355. else {
  51356. var index = this._scene._activeAnimatables.indexOf(this);
  51357. if (index > -1) {
  51358. this._scene._activeAnimatables.splice(index, 1);
  51359. var runtimeAnimations = this._runtimeAnimations;
  51360. for (var index = 0; index < runtimeAnimations.length; index++) {
  51361. runtimeAnimations[index].dispose();
  51362. }
  51363. this._raiseOnAnimationEnd();
  51364. }
  51365. }
  51366. };
  51367. /**
  51368. * Wait asynchronously for the animation to end
  51369. * @returns a promise which will be fullfilled when the animation ends
  51370. */
  51371. Animatable.prototype.waitAsync = function () {
  51372. var _this = this;
  51373. return new Promise(function (resolve, reject) {
  51374. _this.onAnimationEndObservable.add(function () {
  51375. resolve(_this);
  51376. }, undefined, undefined, _this, true);
  51377. });
  51378. };
  51379. /** @hidden */
  51380. Animatable.prototype._animate = function (delay) {
  51381. if (this._paused) {
  51382. this.animationStarted = false;
  51383. if (this._pausedDelay === null) {
  51384. this._pausedDelay = delay;
  51385. }
  51386. return true;
  51387. }
  51388. if (this._localDelayOffset === null) {
  51389. this._localDelayOffset = delay;
  51390. this._pausedDelay = null;
  51391. }
  51392. else if (this._pausedDelay !== null) {
  51393. this._localDelayOffset += delay - this._pausedDelay;
  51394. this._pausedDelay = null;
  51395. }
  51396. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51397. return true;
  51398. }
  51399. // Animating
  51400. var running = false;
  51401. var runtimeAnimations = this._runtimeAnimations;
  51402. var index;
  51403. for (index = 0; index < runtimeAnimations.length; index++) {
  51404. var animation = runtimeAnimations[index];
  51405. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51406. running = running || isRunning;
  51407. }
  51408. this.animationStarted = running;
  51409. if (!running) {
  51410. if (this.disposeOnEnd) {
  51411. // Remove from active animatables
  51412. index = this._scene._activeAnimatables.indexOf(this);
  51413. this._scene._activeAnimatables.splice(index, 1);
  51414. // Dispose all runtime animations
  51415. for (index = 0; index < runtimeAnimations.length; index++) {
  51416. runtimeAnimations[index].dispose();
  51417. }
  51418. }
  51419. this._raiseOnAnimationEnd();
  51420. if (this.disposeOnEnd) {
  51421. this.onAnimationEnd = null;
  51422. this.onAnimationEndObservable.clear();
  51423. }
  51424. }
  51425. return running;
  51426. };
  51427. return Animatable;
  51428. }());
  51429. BABYLON.Animatable = Animatable;
  51430. })(BABYLON || (BABYLON = {}));
  51431. //# sourceMappingURL=babylon.animatable.js.map
  51432. var BABYLON;
  51433. (function (BABYLON) {
  51434. var EasingFunction = /** @class */ (function () {
  51435. function EasingFunction() {
  51436. // Properties
  51437. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51438. }
  51439. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51440. get: function () {
  51441. return EasingFunction._EASINGMODE_EASEIN;
  51442. },
  51443. enumerable: true,
  51444. configurable: true
  51445. });
  51446. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51447. get: function () {
  51448. return EasingFunction._EASINGMODE_EASEOUT;
  51449. },
  51450. enumerable: true,
  51451. configurable: true
  51452. });
  51453. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51454. get: function () {
  51455. return EasingFunction._EASINGMODE_EASEINOUT;
  51456. },
  51457. enumerable: true,
  51458. configurable: true
  51459. });
  51460. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51461. var n = Math.min(Math.max(easingMode, 0), 2);
  51462. this._easingMode = n;
  51463. };
  51464. EasingFunction.prototype.getEasingMode = function () {
  51465. return this._easingMode;
  51466. };
  51467. EasingFunction.prototype.easeInCore = function (gradient) {
  51468. throw new Error('You must implement this method');
  51469. };
  51470. EasingFunction.prototype.ease = function (gradient) {
  51471. switch (this._easingMode) {
  51472. case EasingFunction.EASINGMODE_EASEIN:
  51473. return this.easeInCore(gradient);
  51474. case EasingFunction.EASINGMODE_EASEOUT:
  51475. return (1 - this.easeInCore(1 - gradient));
  51476. }
  51477. if (gradient >= 0.5) {
  51478. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51479. }
  51480. return (this.easeInCore(gradient * 2) * 0.5);
  51481. };
  51482. //Statics
  51483. EasingFunction._EASINGMODE_EASEIN = 0;
  51484. EasingFunction._EASINGMODE_EASEOUT = 1;
  51485. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51486. return EasingFunction;
  51487. }());
  51488. BABYLON.EasingFunction = EasingFunction;
  51489. var CircleEase = /** @class */ (function (_super) {
  51490. __extends(CircleEase, _super);
  51491. function CircleEase() {
  51492. return _super !== null && _super.apply(this, arguments) || this;
  51493. }
  51494. CircleEase.prototype.easeInCore = function (gradient) {
  51495. gradient = Math.max(0, Math.min(1, gradient));
  51496. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51497. };
  51498. return CircleEase;
  51499. }(EasingFunction));
  51500. BABYLON.CircleEase = CircleEase;
  51501. var BackEase = /** @class */ (function (_super) {
  51502. __extends(BackEase, _super);
  51503. function BackEase(amplitude) {
  51504. if (amplitude === void 0) { amplitude = 1; }
  51505. var _this = _super.call(this) || this;
  51506. _this.amplitude = amplitude;
  51507. return _this;
  51508. }
  51509. BackEase.prototype.easeInCore = function (gradient) {
  51510. var num = Math.max(0, this.amplitude);
  51511. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51512. };
  51513. return BackEase;
  51514. }(EasingFunction));
  51515. BABYLON.BackEase = BackEase;
  51516. var BounceEase = /** @class */ (function (_super) {
  51517. __extends(BounceEase, _super);
  51518. function BounceEase(bounces, bounciness) {
  51519. if (bounces === void 0) { bounces = 3; }
  51520. if (bounciness === void 0) { bounciness = 2; }
  51521. var _this = _super.call(this) || this;
  51522. _this.bounces = bounces;
  51523. _this.bounciness = bounciness;
  51524. return _this;
  51525. }
  51526. BounceEase.prototype.easeInCore = function (gradient) {
  51527. var y = Math.max(0.0, this.bounces);
  51528. var bounciness = this.bounciness;
  51529. if (bounciness <= 1.0) {
  51530. bounciness = 1.001;
  51531. }
  51532. var num9 = Math.pow(bounciness, y);
  51533. var num5 = 1.0 - bounciness;
  51534. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51535. var num15 = gradient * num4;
  51536. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51537. var num3 = Math.floor(num65);
  51538. var num13 = num3 + 1.0;
  51539. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51540. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51541. var num7 = (num8 + num12) * 0.5;
  51542. var num6 = gradient - num7;
  51543. var num2 = num7 - num8;
  51544. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51545. };
  51546. return BounceEase;
  51547. }(EasingFunction));
  51548. BABYLON.BounceEase = BounceEase;
  51549. var CubicEase = /** @class */ (function (_super) {
  51550. __extends(CubicEase, _super);
  51551. function CubicEase() {
  51552. return _super !== null && _super.apply(this, arguments) || this;
  51553. }
  51554. CubicEase.prototype.easeInCore = function (gradient) {
  51555. return (gradient * gradient * gradient);
  51556. };
  51557. return CubicEase;
  51558. }(EasingFunction));
  51559. BABYLON.CubicEase = CubicEase;
  51560. var ElasticEase = /** @class */ (function (_super) {
  51561. __extends(ElasticEase, _super);
  51562. function ElasticEase(oscillations, springiness) {
  51563. if (oscillations === void 0) { oscillations = 3; }
  51564. if (springiness === void 0) { springiness = 3; }
  51565. var _this = _super.call(this) || this;
  51566. _this.oscillations = oscillations;
  51567. _this.springiness = springiness;
  51568. return _this;
  51569. }
  51570. ElasticEase.prototype.easeInCore = function (gradient) {
  51571. var num2;
  51572. var num3 = Math.max(0.0, this.oscillations);
  51573. var num = Math.max(0.0, this.springiness);
  51574. if (num == 0) {
  51575. num2 = gradient;
  51576. }
  51577. else {
  51578. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51579. }
  51580. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51581. };
  51582. return ElasticEase;
  51583. }(EasingFunction));
  51584. BABYLON.ElasticEase = ElasticEase;
  51585. var ExponentialEase = /** @class */ (function (_super) {
  51586. __extends(ExponentialEase, _super);
  51587. function ExponentialEase(exponent) {
  51588. if (exponent === void 0) { exponent = 2; }
  51589. var _this = _super.call(this) || this;
  51590. _this.exponent = exponent;
  51591. return _this;
  51592. }
  51593. ExponentialEase.prototype.easeInCore = function (gradient) {
  51594. if (this.exponent <= 0) {
  51595. return gradient;
  51596. }
  51597. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51598. };
  51599. return ExponentialEase;
  51600. }(EasingFunction));
  51601. BABYLON.ExponentialEase = ExponentialEase;
  51602. var PowerEase = /** @class */ (function (_super) {
  51603. __extends(PowerEase, _super);
  51604. function PowerEase(power) {
  51605. if (power === void 0) { power = 2; }
  51606. var _this = _super.call(this) || this;
  51607. _this.power = power;
  51608. return _this;
  51609. }
  51610. PowerEase.prototype.easeInCore = function (gradient) {
  51611. var y = Math.max(0.0, this.power);
  51612. return Math.pow(gradient, y);
  51613. };
  51614. return PowerEase;
  51615. }(EasingFunction));
  51616. BABYLON.PowerEase = PowerEase;
  51617. var QuadraticEase = /** @class */ (function (_super) {
  51618. __extends(QuadraticEase, _super);
  51619. function QuadraticEase() {
  51620. return _super !== null && _super.apply(this, arguments) || this;
  51621. }
  51622. QuadraticEase.prototype.easeInCore = function (gradient) {
  51623. return (gradient * gradient);
  51624. };
  51625. return QuadraticEase;
  51626. }(EasingFunction));
  51627. BABYLON.QuadraticEase = QuadraticEase;
  51628. var QuarticEase = /** @class */ (function (_super) {
  51629. __extends(QuarticEase, _super);
  51630. function QuarticEase() {
  51631. return _super !== null && _super.apply(this, arguments) || this;
  51632. }
  51633. QuarticEase.prototype.easeInCore = function (gradient) {
  51634. return (gradient * gradient * gradient * gradient);
  51635. };
  51636. return QuarticEase;
  51637. }(EasingFunction));
  51638. BABYLON.QuarticEase = QuarticEase;
  51639. var QuinticEase = /** @class */ (function (_super) {
  51640. __extends(QuinticEase, _super);
  51641. function QuinticEase() {
  51642. return _super !== null && _super.apply(this, arguments) || this;
  51643. }
  51644. QuinticEase.prototype.easeInCore = function (gradient) {
  51645. return (gradient * gradient * gradient * gradient * gradient);
  51646. };
  51647. return QuinticEase;
  51648. }(EasingFunction));
  51649. BABYLON.QuinticEase = QuinticEase;
  51650. var SineEase = /** @class */ (function (_super) {
  51651. __extends(SineEase, _super);
  51652. function SineEase() {
  51653. return _super !== null && _super.apply(this, arguments) || this;
  51654. }
  51655. SineEase.prototype.easeInCore = function (gradient) {
  51656. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51657. };
  51658. return SineEase;
  51659. }(EasingFunction));
  51660. BABYLON.SineEase = SineEase;
  51661. var BezierCurveEase = /** @class */ (function (_super) {
  51662. __extends(BezierCurveEase, _super);
  51663. function BezierCurveEase(x1, y1, x2, y2) {
  51664. if (x1 === void 0) { x1 = 0; }
  51665. if (y1 === void 0) { y1 = 0; }
  51666. if (x2 === void 0) { x2 = 1; }
  51667. if (y2 === void 0) { y2 = 1; }
  51668. var _this = _super.call(this) || this;
  51669. _this.x1 = x1;
  51670. _this.y1 = y1;
  51671. _this.x2 = x2;
  51672. _this.y2 = y2;
  51673. return _this;
  51674. }
  51675. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51676. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51677. };
  51678. return BezierCurveEase;
  51679. }(EasingFunction));
  51680. BABYLON.BezierCurveEase = BezierCurveEase;
  51681. })(BABYLON || (BABYLON = {}));
  51682. //# sourceMappingURL=babylon.easing.js.map
  51683. var BABYLON;
  51684. (function (BABYLON) {
  51685. /**
  51686. * A Condition applied to an Action
  51687. */
  51688. var Condition = /** @class */ (function () {
  51689. /**
  51690. * Creates a new Condition
  51691. * @param actionManager the manager of the action the condition is applied to
  51692. */
  51693. function Condition(actionManager) {
  51694. this._actionManager = actionManager;
  51695. }
  51696. /**
  51697. * Check if the current condition is valid
  51698. * @returns a boolean
  51699. */
  51700. Condition.prototype.isValid = function () {
  51701. return true;
  51702. };
  51703. /**
  51704. * Internal only
  51705. * @hidden
  51706. */
  51707. Condition.prototype._getProperty = function (propertyPath) {
  51708. return this._actionManager._getProperty(propertyPath);
  51709. };
  51710. /**
  51711. * Internal only
  51712. * @hidden
  51713. */
  51714. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51715. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51716. };
  51717. /**
  51718. * Serialize placeholder for child classes
  51719. * @returns the serialized object
  51720. */
  51721. Condition.prototype.serialize = function () {
  51722. };
  51723. /**
  51724. * Internal only
  51725. * @hidden
  51726. */
  51727. Condition.prototype._serialize = function (serializedCondition) {
  51728. return {
  51729. type: 2,
  51730. children: [],
  51731. name: serializedCondition.name,
  51732. properties: serializedCondition.properties
  51733. };
  51734. };
  51735. return Condition;
  51736. }());
  51737. BABYLON.Condition = Condition;
  51738. /**
  51739. * Defines specific conditional operators as extensions of Condition
  51740. */
  51741. var ValueCondition = /** @class */ (function (_super) {
  51742. __extends(ValueCondition, _super);
  51743. /**
  51744. * Creates a new ValueCondition
  51745. * @param actionManager manager for the action the condition applies to
  51746. * @param target for the action
  51747. * @param propertyPath path to specify the property of the target the conditional operator uses
  51748. * @param value the value compared by the conditional operator against the current value of the property
  51749. * @param operator the conditional operator, default ValueCondition.IsEqual
  51750. */
  51751. function ValueCondition(actionManager, target,
  51752. /** path to specify the property of the target the conditional operator uses */
  51753. propertyPath,
  51754. /** the value compared by the conditional operator against the current value of the property */
  51755. value,
  51756. /** the conditional operator, default ValueCondition.IsEqual */
  51757. operator) {
  51758. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51759. var _this = _super.call(this, actionManager) || this;
  51760. _this.propertyPath = propertyPath;
  51761. _this.value = value;
  51762. _this.operator = operator;
  51763. _this._target = target;
  51764. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51765. _this._property = _this._getProperty(_this.propertyPath);
  51766. return _this;
  51767. }
  51768. Object.defineProperty(ValueCondition, "IsEqual", {
  51769. /**
  51770. * returns the number for IsEqual
  51771. */
  51772. get: function () {
  51773. return ValueCondition._IsEqual;
  51774. },
  51775. enumerable: true,
  51776. configurable: true
  51777. });
  51778. Object.defineProperty(ValueCondition, "IsDifferent", {
  51779. /**
  51780. * Returns the number for IsDifferent
  51781. */
  51782. get: function () {
  51783. return ValueCondition._IsDifferent;
  51784. },
  51785. enumerable: true,
  51786. configurable: true
  51787. });
  51788. Object.defineProperty(ValueCondition, "IsGreater", {
  51789. /**
  51790. * Returns the number for IsGreater
  51791. */
  51792. get: function () {
  51793. return ValueCondition._IsGreater;
  51794. },
  51795. enumerable: true,
  51796. configurable: true
  51797. });
  51798. Object.defineProperty(ValueCondition, "IsLesser", {
  51799. /**
  51800. * Returns the number for IsLesser
  51801. */
  51802. get: function () {
  51803. return ValueCondition._IsLesser;
  51804. },
  51805. enumerable: true,
  51806. configurable: true
  51807. });
  51808. /**
  51809. * Compares the given value with the property value for the specified conditional operator
  51810. * @returns the result of the comparison
  51811. */
  51812. ValueCondition.prototype.isValid = function () {
  51813. switch (this.operator) {
  51814. case ValueCondition.IsGreater:
  51815. return this._effectiveTarget[this._property] > this.value;
  51816. case ValueCondition.IsLesser:
  51817. return this._effectiveTarget[this._property] < this.value;
  51818. case ValueCondition.IsEqual:
  51819. case ValueCondition.IsDifferent:
  51820. var check;
  51821. if (this.value.equals) {
  51822. check = this.value.equals(this._effectiveTarget[this._property]);
  51823. }
  51824. else {
  51825. check = this.value === this._effectiveTarget[this._property];
  51826. }
  51827. return this.operator === ValueCondition.IsEqual ? check : !check;
  51828. }
  51829. return false;
  51830. };
  51831. /**
  51832. * Serialize the ValueCondition into a JSON compatible object
  51833. * @returns serialization object
  51834. */
  51835. ValueCondition.prototype.serialize = function () {
  51836. return this._serialize({
  51837. name: "ValueCondition",
  51838. properties: [
  51839. BABYLON.Action._GetTargetProperty(this._target),
  51840. { name: "propertyPath", value: this.propertyPath },
  51841. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51842. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51843. ]
  51844. });
  51845. };
  51846. /**
  51847. * Gets the name of the conditional operator for the ValueCondition
  51848. * @param operator the conditional operator
  51849. * @returns the name
  51850. */
  51851. ValueCondition.GetOperatorName = function (operator) {
  51852. switch (operator) {
  51853. case ValueCondition._IsEqual: return "IsEqual";
  51854. case ValueCondition._IsDifferent: return "IsDifferent";
  51855. case ValueCondition._IsGreater: return "IsGreater";
  51856. case ValueCondition._IsLesser: return "IsLesser";
  51857. default: return "";
  51858. }
  51859. };
  51860. /**
  51861. * Internal only
  51862. * @hidden
  51863. */
  51864. ValueCondition._IsEqual = 0;
  51865. /**
  51866. * Internal only
  51867. * @hidden
  51868. */
  51869. ValueCondition._IsDifferent = 1;
  51870. /**
  51871. * Internal only
  51872. * @hidden
  51873. */
  51874. ValueCondition._IsGreater = 2;
  51875. /**
  51876. * Internal only
  51877. * @hidden
  51878. */
  51879. ValueCondition._IsLesser = 3;
  51880. return ValueCondition;
  51881. }(Condition));
  51882. BABYLON.ValueCondition = ValueCondition;
  51883. /**
  51884. * Defines a predicate condition as an extension of Condition
  51885. */
  51886. var PredicateCondition = /** @class */ (function (_super) {
  51887. __extends(PredicateCondition, _super);
  51888. /**
  51889. * Creates a new PredicateCondition
  51890. * @param actionManager manager for the action the condition applies to
  51891. * @param predicate defines the predicate function used to validate the condition
  51892. */
  51893. function PredicateCondition(actionManager,
  51894. /** defines the predicate function used to validate the condition */
  51895. predicate) {
  51896. var _this = _super.call(this, actionManager) || this;
  51897. _this.predicate = predicate;
  51898. return _this;
  51899. }
  51900. /**
  51901. * @returns the validity of the predicate condition
  51902. */
  51903. PredicateCondition.prototype.isValid = function () {
  51904. return this.predicate();
  51905. };
  51906. return PredicateCondition;
  51907. }(Condition));
  51908. BABYLON.PredicateCondition = PredicateCondition;
  51909. /**
  51910. * Defines a state condition as an extension of Condition
  51911. */
  51912. var StateCondition = /** @class */ (function (_super) {
  51913. __extends(StateCondition, _super);
  51914. /**
  51915. * Creates a new StateCondition
  51916. * @param actionManager manager for the action the condition applies to
  51917. * @param target of the condition
  51918. * @param value to compare with target state
  51919. */
  51920. function StateCondition(actionManager, target, value) {
  51921. var _this = _super.call(this, actionManager) || this;
  51922. _this.value = value;
  51923. _this._target = target;
  51924. return _this;
  51925. }
  51926. /**
  51927. * @returns the validity of the state
  51928. */
  51929. StateCondition.prototype.isValid = function () {
  51930. return this._target.state === this.value;
  51931. };
  51932. /**
  51933. * Serialize the StateCondition into a JSON compatible object
  51934. * @returns serialization object
  51935. */
  51936. StateCondition.prototype.serialize = function () {
  51937. return this._serialize({
  51938. name: "StateCondition",
  51939. properties: [
  51940. BABYLON.Action._GetTargetProperty(this._target),
  51941. { name: "value", value: this.value }
  51942. ]
  51943. });
  51944. };
  51945. return StateCondition;
  51946. }(Condition));
  51947. BABYLON.StateCondition = StateCondition;
  51948. })(BABYLON || (BABYLON = {}));
  51949. //# sourceMappingURL=babylon.condition.js.map
  51950. var BABYLON;
  51951. (function (BABYLON) {
  51952. /**
  51953. * The action to be carried out following a trigger
  51954. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51955. */
  51956. var Action = /** @class */ (function () {
  51957. /**
  51958. * Creates a new Action
  51959. * @param triggerOptions the trigger, with or without parameters, for the action
  51960. * @param condition an optional determinant of action
  51961. */
  51962. function Action(
  51963. /** the trigger, with or without parameters, for the action */
  51964. triggerOptions, condition) {
  51965. this.triggerOptions = triggerOptions;
  51966. /**
  51967. * An event triggered prior to action being executed.
  51968. */
  51969. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51970. if (triggerOptions.parameter) {
  51971. this.trigger = triggerOptions.trigger;
  51972. this._triggerParameter = triggerOptions.parameter;
  51973. }
  51974. else {
  51975. this.trigger = triggerOptions;
  51976. }
  51977. this._nextActiveAction = this;
  51978. this._condition = condition;
  51979. }
  51980. /**
  51981. * Internal only
  51982. * @hidden
  51983. */
  51984. Action.prototype._prepare = function () {
  51985. };
  51986. /**
  51987. * Gets the trigger parameters
  51988. * @returns the trigger parameters
  51989. */
  51990. Action.prototype.getTriggerParameter = function () {
  51991. return this._triggerParameter;
  51992. };
  51993. /**
  51994. * Internal only - executes current action event
  51995. * @hidden
  51996. */
  51997. Action.prototype._executeCurrent = function (evt) {
  51998. if (this._nextActiveAction._condition) {
  51999. var condition = this._nextActiveAction._condition;
  52000. var currentRenderId = this._actionManager.getScene().getRenderId();
  52001. // We cache the current evaluation for the current frame
  52002. if (condition._evaluationId === currentRenderId) {
  52003. if (!condition._currentResult) {
  52004. return;
  52005. }
  52006. }
  52007. else {
  52008. condition._evaluationId = currentRenderId;
  52009. if (!condition.isValid()) {
  52010. condition._currentResult = false;
  52011. return;
  52012. }
  52013. condition._currentResult = true;
  52014. }
  52015. }
  52016. this.onBeforeExecuteObservable.notifyObservers(this);
  52017. this._nextActiveAction.execute(evt);
  52018. this.skipToNextActiveAction();
  52019. };
  52020. /**
  52021. * Execute placeholder for child classes
  52022. * @param evt optional action event
  52023. */
  52024. Action.prototype.execute = function (evt) {
  52025. };
  52026. /**
  52027. * Skips to next active action
  52028. */
  52029. Action.prototype.skipToNextActiveAction = function () {
  52030. if (this._nextActiveAction._child) {
  52031. if (!this._nextActiveAction._child._actionManager) {
  52032. this._nextActiveAction._child._actionManager = this._actionManager;
  52033. }
  52034. this._nextActiveAction = this._nextActiveAction._child;
  52035. }
  52036. else {
  52037. this._nextActiveAction = this;
  52038. }
  52039. };
  52040. /**
  52041. * Adds action to chain of actions, may be a DoNothingAction
  52042. * @param action defines the next action to execute
  52043. * @returns The action passed in
  52044. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52045. */
  52046. Action.prototype.then = function (action) {
  52047. this._child = action;
  52048. action._actionManager = this._actionManager;
  52049. action._prepare();
  52050. return action;
  52051. };
  52052. /**
  52053. * Internal only
  52054. * @hidden
  52055. */
  52056. Action.prototype._getProperty = function (propertyPath) {
  52057. return this._actionManager._getProperty(propertyPath);
  52058. };
  52059. /**
  52060. * Internal only
  52061. * @hidden
  52062. */
  52063. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52064. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52065. };
  52066. /**
  52067. * Serialize placeholder for child classes
  52068. * @param parent of child
  52069. * @returns the serialized object
  52070. */
  52071. Action.prototype.serialize = function (parent) {
  52072. };
  52073. /**
  52074. * Internal only called by serialize
  52075. * @hidden
  52076. */
  52077. Action.prototype._serialize = function (serializedAction, parent) {
  52078. var serializationObject = {
  52079. type: 1,
  52080. children: [],
  52081. name: serializedAction.name,
  52082. properties: serializedAction.properties || []
  52083. };
  52084. // Serialize child
  52085. if (this._child) {
  52086. this._child.serialize(serializationObject);
  52087. }
  52088. // Check if "this" has a condition
  52089. if (this._condition) {
  52090. var serializedCondition = this._condition.serialize();
  52091. serializedCondition.children.push(serializationObject);
  52092. if (parent) {
  52093. parent.children.push(serializedCondition);
  52094. }
  52095. return serializedCondition;
  52096. }
  52097. if (parent) {
  52098. parent.children.push(serializationObject);
  52099. }
  52100. return serializationObject;
  52101. };
  52102. /**
  52103. * Internal only
  52104. * @hidden
  52105. */
  52106. Action._SerializeValueAsString = function (value) {
  52107. if (typeof value === "number") {
  52108. return value.toString();
  52109. }
  52110. if (typeof value === "boolean") {
  52111. return value ? "true" : "false";
  52112. }
  52113. if (value instanceof BABYLON.Vector2) {
  52114. return value.x + ", " + value.y;
  52115. }
  52116. if (value instanceof BABYLON.Vector3) {
  52117. return value.x + ", " + value.y + ", " + value.z;
  52118. }
  52119. if (value instanceof BABYLON.Color3) {
  52120. return value.r + ", " + value.g + ", " + value.b;
  52121. }
  52122. if (value instanceof BABYLON.Color4) {
  52123. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52124. }
  52125. return value; // string
  52126. };
  52127. /**
  52128. * Internal only
  52129. * @hidden
  52130. */
  52131. Action._GetTargetProperty = function (target) {
  52132. return {
  52133. name: "target",
  52134. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52135. : target instanceof BABYLON.Light ? "LightProperties"
  52136. : target instanceof BABYLON.Camera ? "CameraProperties"
  52137. : "SceneProperties",
  52138. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52139. };
  52140. };
  52141. return Action;
  52142. }());
  52143. BABYLON.Action = Action;
  52144. })(BABYLON || (BABYLON = {}));
  52145. //# sourceMappingURL=babylon.action.js.map
  52146. var BABYLON;
  52147. (function (BABYLON) {
  52148. /**
  52149. * ActionEvent is the event being sent when an action is triggered.
  52150. */
  52151. var ActionEvent = /** @class */ (function () {
  52152. /**
  52153. * Creates a new ActionEvent
  52154. * @param source The mesh or sprite that triggered the action
  52155. * @param pointerX The X mouse cursor position at the time of the event
  52156. * @param pointerY The Y mouse cursor position at the time of the event
  52157. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52158. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52159. * @param additionalData additional data for the event
  52160. */
  52161. function ActionEvent(
  52162. /** The mesh or sprite that triggered the action */
  52163. source,
  52164. /** The X mouse cursor position at the time of the event */
  52165. pointerX,
  52166. /** The Y mouse cursor position at the time of the event */
  52167. pointerY,
  52168. /** The mesh that is currently pointed at (can be null) */
  52169. meshUnderPointer,
  52170. /** the original (browser) event that triggered the ActionEvent */
  52171. sourceEvent,
  52172. /** additional data for the event */
  52173. additionalData) {
  52174. this.source = source;
  52175. this.pointerX = pointerX;
  52176. this.pointerY = pointerY;
  52177. this.meshUnderPointer = meshUnderPointer;
  52178. this.sourceEvent = sourceEvent;
  52179. this.additionalData = additionalData;
  52180. }
  52181. /**
  52182. * Helper function to auto-create an ActionEvent from a source mesh.
  52183. * @param source The source mesh that triggered the event
  52184. * @param evt The original (browser) event
  52185. * @param additionalData additional data for the event
  52186. * @returns the new ActionEvent
  52187. */
  52188. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52189. var scene = source.getScene();
  52190. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52191. };
  52192. /**
  52193. * Helper function to auto-create an ActionEvent from a source sprite
  52194. * @param source The source sprite that triggered the event
  52195. * @param scene Scene associated with the sprite
  52196. * @param evt The original (browser) event
  52197. * @param additionalData additional data for the event
  52198. * @returns the new ActionEvent
  52199. */
  52200. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52201. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52202. };
  52203. /**
  52204. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52205. * @param scene the scene where the event occurred
  52206. * @param evt The original (browser) event
  52207. * @returns the new ActionEvent
  52208. */
  52209. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52210. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52211. };
  52212. /**
  52213. * Helper function to auto-create an ActionEvent from a primitive
  52214. * @param prim defines the target primitive
  52215. * @param pointerPos defines the pointer position
  52216. * @param evt The original (browser) event
  52217. * @param additionalData additional data for the event
  52218. * @returns the new ActionEvent
  52219. */
  52220. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52221. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52222. };
  52223. return ActionEvent;
  52224. }());
  52225. BABYLON.ActionEvent = ActionEvent;
  52226. /**
  52227. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52228. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52229. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52230. */
  52231. var ActionManager = /** @class */ (function () {
  52232. /**
  52233. * Creates a new action manager
  52234. * @param scene defines the hosting scene
  52235. */
  52236. function ActionManager(scene) {
  52237. // Members
  52238. /** Gets the list of actions */
  52239. this.actions = new Array();
  52240. /** Gets the cursor to use when hovering items */
  52241. this.hoverCursor = '';
  52242. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52243. scene.actionManagers.push(this);
  52244. }
  52245. Object.defineProperty(ActionManager, "NothingTrigger", {
  52246. /**
  52247. * Nothing
  52248. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52249. */
  52250. get: function () {
  52251. return ActionManager._NothingTrigger;
  52252. },
  52253. enumerable: true,
  52254. configurable: true
  52255. });
  52256. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52257. /**
  52258. * On pick
  52259. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52260. */
  52261. get: function () {
  52262. return ActionManager._OnPickTrigger;
  52263. },
  52264. enumerable: true,
  52265. configurable: true
  52266. });
  52267. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52268. /**
  52269. * On left pick
  52270. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52271. */
  52272. get: function () {
  52273. return ActionManager._OnLeftPickTrigger;
  52274. },
  52275. enumerable: true,
  52276. configurable: true
  52277. });
  52278. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52279. /**
  52280. * On right pick
  52281. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52282. */
  52283. get: function () {
  52284. return ActionManager._OnRightPickTrigger;
  52285. },
  52286. enumerable: true,
  52287. configurable: true
  52288. });
  52289. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52290. /**
  52291. * On center pick
  52292. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52293. */
  52294. get: function () {
  52295. return ActionManager._OnCenterPickTrigger;
  52296. },
  52297. enumerable: true,
  52298. configurable: true
  52299. });
  52300. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52301. /**
  52302. * On pick down
  52303. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52304. */
  52305. get: function () {
  52306. return ActionManager._OnPickDownTrigger;
  52307. },
  52308. enumerable: true,
  52309. configurable: true
  52310. });
  52311. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52312. /**
  52313. * On double pick
  52314. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52315. */
  52316. get: function () {
  52317. return ActionManager._OnDoublePickTrigger;
  52318. },
  52319. enumerable: true,
  52320. configurable: true
  52321. });
  52322. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52323. /**
  52324. * On pick up
  52325. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52326. */
  52327. get: function () {
  52328. return ActionManager._OnPickUpTrigger;
  52329. },
  52330. enumerable: true,
  52331. configurable: true
  52332. });
  52333. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52334. /**
  52335. * On pick out.
  52336. * This trigger will only be raised if you also declared a OnPickDown
  52337. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52338. */
  52339. get: function () {
  52340. return ActionManager._OnPickOutTrigger;
  52341. },
  52342. enumerable: true,
  52343. configurable: true
  52344. });
  52345. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52346. /**
  52347. * On long press
  52348. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52349. */
  52350. get: function () {
  52351. return ActionManager._OnLongPressTrigger;
  52352. },
  52353. enumerable: true,
  52354. configurable: true
  52355. });
  52356. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52357. /**
  52358. * On pointer over
  52359. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52360. */
  52361. get: function () {
  52362. return ActionManager._OnPointerOverTrigger;
  52363. },
  52364. enumerable: true,
  52365. configurable: true
  52366. });
  52367. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52368. /**
  52369. * On pointer out
  52370. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52371. */
  52372. get: function () {
  52373. return ActionManager._OnPointerOutTrigger;
  52374. },
  52375. enumerable: true,
  52376. configurable: true
  52377. });
  52378. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52379. /**
  52380. * On every frame
  52381. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52382. */
  52383. get: function () {
  52384. return ActionManager._OnEveryFrameTrigger;
  52385. },
  52386. enumerable: true,
  52387. configurable: true
  52388. });
  52389. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52390. /**
  52391. * On intersection enter
  52392. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52393. */
  52394. get: function () {
  52395. return ActionManager._OnIntersectionEnterTrigger;
  52396. },
  52397. enumerable: true,
  52398. configurable: true
  52399. });
  52400. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52401. /**
  52402. * On intersection exit
  52403. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52404. */
  52405. get: function () {
  52406. return ActionManager._OnIntersectionExitTrigger;
  52407. },
  52408. enumerable: true,
  52409. configurable: true
  52410. });
  52411. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52412. /**
  52413. * On key down
  52414. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52415. */
  52416. get: function () {
  52417. return ActionManager._OnKeyDownTrigger;
  52418. },
  52419. enumerable: true,
  52420. configurable: true
  52421. });
  52422. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52423. /**
  52424. * On key up
  52425. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52426. */
  52427. get: function () {
  52428. return ActionManager._OnKeyUpTrigger;
  52429. },
  52430. enumerable: true,
  52431. configurable: true
  52432. });
  52433. // Methods
  52434. /**
  52435. * Releases all associated resources
  52436. */
  52437. ActionManager.prototype.dispose = function () {
  52438. var index = this._scene.actionManagers.indexOf(this);
  52439. for (var i = 0; i < this.actions.length; i++) {
  52440. var action = this.actions[i];
  52441. ActionManager.Triggers[action.trigger]--;
  52442. if (ActionManager.Triggers[action.trigger] === 0) {
  52443. delete ActionManager.Triggers[action.trigger];
  52444. }
  52445. }
  52446. if (index > -1) {
  52447. this._scene.actionManagers.splice(index, 1);
  52448. }
  52449. };
  52450. /**
  52451. * Gets hosting scene
  52452. * @returns the hosting scene
  52453. */
  52454. ActionManager.prototype.getScene = function () {
  52455. return this._scene;
  52456. };
  52457. /**
  52458. * Does this action manager handles actions of any of the given triggers
  52459. * @param triggers defines the triggers to be tested
  52460. * @return a boolean indicating whether one (or more) of the triggers is handled
  52461. */
  52462. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52463. for (var index = 0; index < this.actions.length; index++) {
  52464. var action = this.actions[index];
  52465. if (triggers.indexOf(action.trigger) > -1) {
  52466. return true;
  52467. }
  52468. }
  52469. return false;
  52470. };
  52471. /**
  52472. * Does this action manager handles actions of a given trigger
  52473. * @param trigger defines the trigger to be tested
  52474. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52475. * @return whether the trigger is handled
  52476. */
  52477. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52478. for (var index = 0; index < this.actions.length; index++) {
  52479. var action = this.actions[index];
  52480. if (action.trigger === trigger) {
  52481. if (parameterPredicate) {
  52482. if (parameterPredicate(action.getTriggerParameter())) {
  52483. return true;
  52484. }
  52485. }
  52486. else {
  52487. return true;
  52488. }
  52489. }
  52490. }
  52491. return false;
  52492. };
  52493. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52494. /**
  52495. * Does this action manager has pointer triggers
  52496. */
  52497. get: function () {
  52498. for (var index = 0; index < this.actions.length; index++) {
  52499. var action = this.actions[index];
  52500. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52501. return true;
  52502. }
  52503. }
  52504. return false;
  52505. },
  52506. enumerable: true,
  52507. configurable: true
  52508. });
  52509. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52510. /**
  52511. * Does this action manager has pick triggers
  52512. */
  52513. get: function () {
  52514. for (var index = 0; index < this.actions.length; index++) {
  52515. var action = this.actions[index];
  52516. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52517. return true;
  52518. }
  52519. }
  52520. return false;
  52521. },
  52522. enumerable: true,
  52523. configurable: true
  52524. });
  52525. Object.defineProperty(ActionManager, "HasTriggers", {
  52526. /**
  52527. * Does exist one action manager with at least one trigger
  52528. **/
  52529. get: function () {
  52530. for (var t in ActionManager.Triggers) {
  52531. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52532. return true;
  52533. }
  52534. }
  52535. return false;
  52536. },
  52537. enumerable: true,
  52538. configurable: true
  52539. });
  52540. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52541. /**
  52542. * Does exist one action manager with at least one pick trigger
  52543. **/
  52544. get: function () {
  52545. for (var t in ActionManager.Triggers) {
  52546. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52547. var t_int = parseInt(t);
  52548. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52549. return true;
  52550. }
  52551. }
  52552. }
  52553. return false;
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. /**
  52559. * Does exist one action manager that handles actions of a given trigger
  52560. * @param trigger defines the trigger to be tested
  52561. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52562. **/
  52563. ActionManager.HasSpecificTrigger = function (trigger) {
  52564. for (var t in ActionManager.Triggers) {
  52565. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52566. var t_int = parseInt(t);
  52567. if (t_int === trigger) {
  52568. return true;
  52569. }
  52570. }
  52571. }
  52572. return false;
  52573. };
  52574. /**
  52575. * Registers an action to this action manager
  52576. * @param action defines the action to be registered
  52577. * @return the action amended (prepared) after registration
  52578. */
  52579. ActionManager.prototype.registerAction = function (action) {
  52580. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52581. if (this.getScene().actionManager !== this) {
  52582. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52583. return null;
  52584. }
  52585. }
  52586. this.actions.push(action);
  52587. if (ActionManager.Triggers[action.trigger]) {
  52588. ActionManager.Triggers[action.trigger]++;
  52589. }
  52590. else {
  52591. ActionManager.Triggers[action.trigger] = 1;
  52592. }
  52593. action._actionManager = this;
  52594. action._prepare();
  52595. return action;
  52596. };
  52597. /**
  52598. * Unregisters an action to this action manager
  52599. * @param action defines the action to be unregistered
  52600. * @return a boolean indicating whether the action has been unregistered
  52601. */
  52602. ActionManager.prototype.unregisterAction = function (action) {
  52603. var index = this.actions.indexOf(action);
  52604. if (index !== -1) {
  52605. this.actions.splice(index, 1);
  52606. ActionManager.Triggers[action.trigger] -= 1;
  52607. if (ActionManager.Triggers[action.trigger] === 0) {
  52608. delete ActionManager.Triggers[action.trigger];
  52609. }
  52610. delete action._actionManager;
  52611. return true;
  52612. }
  52613. return false;
  52614. };
  52615. /**
  52616. * Process a specific trigger
  52617. * @param trigger defines the trigger to process
  52618. * @param evt defines the event details to be processed
  52619. */
  52620. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52621. for (var index = 0; index < this.actions.length; index++) {
  52622. var action = this.actions[index];
  52623. if (action.trigger === trigger) {
  52624. if (evt) {
  52625. if (trigger === ActionManager.OnKeyUpTrigger
  52626. || trigger === ActionManager.OnKeyDownTrigger) {
  52627. var parameter = action.getTriggerParameter();
  52628. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52629. if (!parameter.toLowerCase) {
  52630. continue;
  52631. }
  52632. var lowerCase = parameter.toLowerCase();
  52633. if (lowerCase !== evt.sourceEvent.key) {
  52634. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52635. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52636. if (actualkey !== lowerCase) {
  52637. continue;
  52638. }
  52639. }
  52640. }
  52641. }
  52642. }
  52643. action._executeCurrent(evt);
  52644. }
  52645. }
  52646. };
  52647. /** @hidden */
  52648. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52649. var properties = propertyPath.split(".");
  52650. for (var index = 0; index < properties.length - 1; index++) {
  52651. target = target[properties[index]];
  52652. }
  52653. return target;
  52654. };
  52655. /** @hidden */
  52656. ActionManager.prototype._getProperty = function (propertyPath) {
  52657. var properties = propertyPath.split(".");
  52658. return properties[properties.length - 1];
  52659. };
  52660. /**
  52661. * Serialize this manager to a JSON object
  52662. * @param name defines the property name to store this manager
  52663. * @returns a JSON representation of this manager
  52664. */
  52665. ActionManager.prototype.serialize = function (name) {
  52666. var root = {
  52667. children: new Array(),
  52668. name: name,
  52669. type: 3,
  52670. properties: new Array() // Empty for root but required
  52671. };
  52672. for (var i = 0; i < this.actions.length; i++) {
  52673. var triggerObject = {
  52674. type: 0,
  52675. children: new Array(),
  52676. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52677. properties: new Array()
  52678. };
  52679. var triggerOptions = this.actions[i].triggerOptions;
  52680. if (triggerOptions && typeof triggerOptions !== "number") {
  52681. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52682. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52683. }
  52684. else {
  52685. var parameter = {};
  52686. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52687. if (triggerOptions.parameter.mesh) {
  52688. parameter._meshId = triggerOptions.parameter.mesh.id;
  52689. }
  52690. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52691. }
  52692. }
  52693. // Serialize child action, recursively
  52694. this.actions[i].serialize(triggerObject);
  52695. // Add serialized trigger
  52696. root.children.push(triggerObject);
  52697. }
  52698. return root;
  52699. };
  52700. /**
  52701. * Creates a new ActionManager from a JSON data
  52702. * @param parsedActions defines the JSON data to read from
  52703. * @param object defines the hosting mesh
  52704. * @param scene defines the hosting scene
  52705. */
  52706. ActionManager.Parse = function (parsedActions, object, scene) {
  52707. var actionManager = new ActionManager(scene);
  52708. if (object === null)
  52709. scene.actionManager = actionManager;
  52710. else
  52711. object.actionManager = actionManager;
  52712. // instanciate a new object
  52713. var instanciate = function (name, params) {
  52714. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52715. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52716. newInstance.constructor.apply(newInstance, params);
  52717. return newInstance;
  52718. };
  52719. var parseParameter = function (name, value, target, propertyPath) {
  52720. if (propertyPath === null) {
  52721. // String, boolean or float
  52722. var floatValue = parseFloat(value);
  52723. if (value === "true" || value === "false")
  52724. return value === "true";
  52725. else
  52726. return isNaN(floatValue) ? value : floatValue;
  52727. }
  52728. var effectiveTarget = propertyPath.split(".");
  52729. var values = value.split(",");
  52730. // Get effective Target
  52731. for (var i = 0; i < effectiveTarget.length; i++) {
  52732. target = target[effectiveTarget[i]];
  52733. }
  52734. // Return appropriate value with its type
  52735. if (typeof (target) === "boolean")
  52736. return values[0] === "true";
  52737. if (typeof (target) === "string")
  52738. return values[0];
  52739. // Parameters with multiple values such as Vector3 etc.
  52740. var split = new Array();
  52741. for (var i = 0; i < values.length; i++)
  52742. split.push(parseFloat(values[i]));
  52743. if (target instanceof BABYLON.Vector3)
  52744. return BABYLON.Vector3.FromArray(split);
  52745. if (target instanceof BABYLON.Vector4)
  52746. return BABYLON.Vector4.FromArray(split);
  52747. if (target instanceof BABYLON.Color3)
  52748. return BABYLON.Color3.FromArray(split);
  52749. if (target instanceof BABYLON.Color4)
  52750. return BABYLON.Color4.FromArray(split);
  52751. return parseFloat(values[0]);
  52752. };
  52753. // traverse graph per trigger
  52754. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52755. if (combineArray === void 0) { combineArray = null; }
  52756. if (parsedAction.detached)
  52757. return;
  52758. var parameters = new Array();
  52759. var target = null;
  52760. var propertyPath = null;
  52761. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52762. // Parameters
  52763. if (parsedAction.type === 2)
  52764. parameters.push(actionManager);
  52765. else
  52766. parameters.push(trigger);
  52767. if (combine) {
  52768. var actions = new Array();
  52769. for (var j = 0; j < parsedAction.combine.length; j++) {
  52770. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52771. }
  52772. parameters.push(actions);
  52773. }
  52774. else {
  52775. for (var i = 0; i < parsedAction.properties.length; i++) {
  52776. var value = parsedAction.properties[i].value;
  52777. var name = parsedAction.properties[i].name;
  52778. var targetType = parsedAction.properties[i].targetType;
  52779. if (name === "target")
  52780. if (targetType !== null && targetType === "SceneProperties")
  52781. value = target = scene;
  52782. else
  52783. value = target = scene.getNodeByName(value);
  52784. else if (name === "parent")
  52785. value = scene.getNodeByName(value);
  52786. else if (name === "sound")
  52787. value = scene.getSoundByName(value);
  52788. else if (name !== "propertyPath") {
  52789. if (parsedAction.type === 2 && name === "operator")
  52790. value = BABYLON.ValueCondition[value];
  52791. else
  52792. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52793. }
  52794. else {
  52795. propertyPath = value;
  52796. }
  52797. parameters.push(value);
  52798. }
  52799. }
  52800. if (combineArray === null) {
  52801. parameters.push(condition);
  52802. }
  52803. else {
  52804. parameters.push(null);
  52805. }
  52806. // If interpolate value action
  52807. if (parsedAction.name === "InterpolateValueAction") {
  52808. var param = parameters[parameters.length - 2];
  52809. parameters[parameters.length - 1] = param;
  52810. parameters[parameters.length - 2] = condition;
  52811. }
  52812. // Action or condition(s) and not CombineAction
  52813. var newAction = instanciate(parsedAction.name, parameters);
  52814. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52815. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52816. if (action)
  52817. action.then(nothing);
  52818. else
  52819. actionManager.registerAction(nothing);
  52820. action = nothing;
  52821. }
  52822. if (combineArray === null) {
  52823. if (newAction instanceof BABYLON.Condition) {
  52824. condition = newAction;
  52825. newAction = action;
  52826. }
  52827. else {
  52828. condition = null;
  52829. if (action)
  52830. action.then(newAction);
  52831. else
  52832. actionManager.registerAction(newAction);
  52833. }
  52834. }
  52835. else {
  52836. combineArray.push(newAction);
  52837. }
  52838. for (var i = 0; i < parsedAction.children.length; i++)
  52839. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52840. };
  52841. // triggers
  52842. for (var i = 0; i < parsedActions.children.length; i++) {
  52843. var triggerParams;
  52844. var trigger = parsedActions.children[i];
  52845. if (trigger.properties.length > 0) {
  52846. var param = trigger.properties[0].value;
  52847. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52848. if (value._meshId) {
  52849. value.mesh = scene.getMeshByID(value._meshId);
  52850. }
  52851. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52852. }
  52853. else
  52854. triggerParams = ActionManager[trigger.name];
  52855. for (var j = 0; j < trigger.children.length; j++) {
  52856. if (!trigger.detached)
  52857. traverse(trigger.children[j], triggerParams, null, null);
  52858. }
  52859. }
  52860. };
  52861. /**
  52862. * Get a trigger name by index
  52863. * @param trigger defines the trigger index
  52864. * @returns a trigger name
  52865. */
  52866. ActionManager.GetTriggerName = function (trigger) {
  52867. switch (trigger) {
  52868. case 0: return "NothingTrigger";
  52869. case 1: return "OnPickTrigger";
  52870. case 2: return "OnLeftPickTrigger";
  52871. case 3: return "OnRightPickTrigger";
  52872. case 4: return "OnCenterPickTrigger";
  52873. case 5: return "OnPickDownTrigger";
  52874. case 6: return "OnPickUpTrigger";
  52875. case 7: return "OnLongPressTrigger";
  52876. case 8: return "OnPointerOverTrigger";
  52877. case 9: return "OnPointerOutTrigger";
  52878. case 10: return "OnEveryFrameTrigger";
  52879. case 11: return "OnIntersectionEnterTrigger";
  52880. case 12: return "OnIntersectionExitTrigger";
  52881. case 13: return "OnKeyDownTrigger";
  52882. case 14: return "OnKeyUpTrigger";
  52883. case 15: return "OnPickOutTrigger";
  52884. default: return "";
  52885. }
  52886. };
  52887. // Statics
  52888. ActionManager._NothingTrigger = 0;
  52889. ActionManager._OnPickTrigger = 1;
  52890. ActionManager._OnLeftPickTrigger = 2;
  52891. ActionManager._OnRightPickTrigger = 3;
  52892. ActionManager._OnCenterPickTrigger = 4;
  52893. ActionManager._OnPickDownTrigger = 5;
  52894. ActionManager._OnDoublePickTrigger = 6;
  52895. ActionManager._OnPickUpTrigger = 7;
  52896. ActionManager._OnLongPressTrigger = 8;
  52897. ActionManager._OnPointerOverTrigger = 9;
  52898. ActionManager._OnPointerOutTrigger = 10;
  52899. ActionManager._OnEveryFrameTrigger = 11;
  52900. ActionManager._OnIntersectionEnterTrigger = 12;
  52901. ActionManager._OnIntersectionExitTrigger = 13;
  52902. ActionManager._OnKeyDownTrigger = 14;
  52903. ActionManager._OnKeyUpTrigger = 15;
  52904. ActionManager._OnPickOutTrigger = 16;
  52905. /** Gets the list of active triggers */
  52906. ActionManager.Triggers = {};
  52907. return ActionManager;
  52908. }());
  52909. BABYLON.ActionManager = ActionManager;
  52910. })(BABYLON || (BABYLON = {}));
  52911. //# sourceMappingURL=babylon.actionManager.js.map
  52912. var BABYLON;
  52913. (function (BABYLON) {
  52914. var InterpolateValueAction = /** @class */ (function (_super) {
  52915. __extends(InterpolateValueAction, _super);
  52916. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52917. if (duration === void 0) { duration = 1000; }
  52918. var _this = _super.call(this, triggerOptions, condition) || this;
  52919. _this.propertyPath = propertyPath;
  52920. _this.value = value;
  52921. _this.duration = duration;
  52922. _this.stopOtherAnimations = stopOtherAnimations;
  52923. _this.onInterpolationDone = onInterpolationDone;
  52924. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52925. _this._target = _this._effectiveTarget = target;
  52926. return _this;
  52927. }
  52928. InterpolateValueAction.prototype._prepare = function () {
  52929. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52930. this._property = this._getProperty(this.propertyPath);
  52931. };
  52932. InterpolateValueAction.prototype.execute = function () {
  52933. var _this = this;
  52934. var scene = this._actionManager.getScene();
  52935. var keys = [
  52936. {
  52937. frame: 0,
  52938. value: this._effectiveTarget[this._property]
  52939. }, {
  52940. frame: 100,
  52941. value: this.value
  52942. }
  52943. ];
  52944. var dataType;
  52945. if (typeof this.value === "number") {
  52946. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52947. }
  52948. else if (this.value instanceof BABYLON.Color3) {
  52949. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52950. }
  52951. else if (this.value instanceof BABYLON.Vector3) {
  52952. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52953. }
  52954. else if (this.value instanceof BABYLON.Matrix) {
  52955. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52956. }
  52957. else if (this.value instanceof BABYLON.Quaternion) {
  52958. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52959. }
  52960. else {
  52961. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52962. return;
  52963. }
  52964. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52965. animation.setKeys(keys);
  52966. if (this.stopOtherAnimations) {
  52967. scene.stopAnimation(this._effectiveTarget);
  52968. }
  52969. var wrapper = function () {
  52970. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52971. if (_this.onInterpolationDone) {
  52972. _this.onInterpolationDone();
  52973. }
  52974. };
  52975. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52976. };
  52977. InterpolateValueAction.prototype.serialize = function (parent) {
  52978. return _super.prototype._serialize.call(this, {
  52979. name: "InterpolateValueAction",
  52980. properties: [
  52981. BABYLON.Action._GetTargetProperty(this._target),
  52982. { name: "propertyPath", value: this.propertyPath },
  52983. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52984. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52985. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52986. ]
  52987. }, parent);
  52988. };
  52989. return InterpolateValueAction;
  52990. }(BABYLON.Action));
  52991. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52992. })(BABYLON || (BABYLON = {}));
  52993. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52994. var BABYLON;
  52995. (function (BABYLON) {
  52996. var SwitchBooleanAction = /** @class */ (function (_super) {
  52997. __extends(SwitchBooleanAction, _super);
  52998. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52999. var _this = _super.call(this, triggerOptions, condition) || this;
  53000. _this.propertyPath = propertyPath;
  53001. _this._target = _this._effectiveTarget = target;
  53002. return _this;
  53003. }
  53004. SwitchBooleanAction.prototype._prepare = function () {
  53005. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53006. this._property = this._getProperty(this.propertyPath);
  53007. };
  53008. SwitchBooleanAction.prototype.execute = function () {
  53009. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53010. };
  53011. SwitchBooleanAction.prototype.serialize = function (parent) {
  53012. return _super.prototype._serialize.call(this, {
  53013. name: "SwitchBooleanAction",
  53014. properties: [
  53015. BABYLON.Action._GetTargetProperty(this._target),
  53016. { name: "propertyPath", value: this.propertyPath }
  53017. ]
  53018. }, parent);
  53019. };
  53020. return SwitchBooleanAction;
  53021. }(BABYLON.Action));
  53022. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53023. var SetStateAction = /** @class */ (function (_super) {
  53024. __extends(SetStateAction, _super);
  53025. function SetStateAction(triggerOptions, target, value, condition) {
  53026. var _this = _super.call(this, triggerOptions, condition) || this;
  53027. _this.value = value;
  53028. _this._target = target;
  53029. return _this;
  53030. }
  53031. SetStateAction.prototype.execute = function () {
  53032. this._target.state = this.value;
  53033. };
  53034. SetStateAction.prototype.serialize = function (parent) {
  53035. return _super.prototype._serialize.call(this, {
  53036. name: "SetStateAction",
  53037. properties: [
  53038. BABYLON.Action._GetTargetProperty(this._target),
  53039. { name: "value", value: this.value }
  53040. ]
  53041. }, parent);
  53042. };
  53043. return SetStateAction;
  53044. }(BABYLON.Action));
  53045. BABYLON.SetStateAction = SetStateAction;
  53046. var SetValueAction = /** @class */ (function (_super) {
  53047. __extends(SetValueAction, _super);
  53048. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53049. var _this = _super.call(this, triggerOptions, condition) || this;
  53050. _this.propertyPath = propertyPath;
  53051. _this.value = value;
  53052. _this._target = _this._effectiveTarget = target;
  53053. return _this;
  53054. }
  53055. SetValueAction.prototype._prepare = function () {
  53056. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53057. this._property = this._getProperty(this.propertyPath);
  53058. };
  53059. SetValueAction.prototype.execute = function () {
  53060. this._effectiveTarget[this._property] = this.value;
  53061. if (this._target.markAsDirty) {
  53062. this._target.markAsDirty(this._property);
  53063. }
  53064. };
  53065. SetValueAction.prototype.serialize = function (parent) {
  53066. return _super.prototype._serialize.call(this, {
  53067. name: "SetValueAction",
  53068. properties: [
  53069. BABYLON.Action._GetTargetProperty(this._target),
  53070. { name: "propertyPath", value: this.propertyPath },
  53071. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53072. ]
  53073. }, parent);
  53074. };
  53075. return SetValueAction;
  53076. }(BABYLON.Action));
  53077. BABYLON.SetValueAction = SetValueAction;
  53078. var IncrementValueAction = /** @class */ (function (_super) {
  53079. __extends(IncrementValueAction, _super);
  53080. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53081. var _this = _super.call(this, triggerOptions, condition) || this;
  53082. _this.propertyPath = propertyPath;
  53083. _this.value = value;
  53084. _this._target = _this._effectiveTarget = target;
  53085. return _this;
  53086. }
  53087. IncrementValueAction.prototype._prepare = function () {
  53088. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53089. this._property = this._getProperty(this.propertyPath);
  53090. if (typeof this._effectiveTarget[this._property] !== "number") {
  53091. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53092. }
  53093. };
  53094. IncrementValueAction.prototype.execute = function () {
  53095. this._effectiveTarget[this._property] += this.value;
  53096. if (this._target.markAsDirty) {
  53097. this._target.markAsDirty(this._property);
  53098. }
  53099. };
  53100. IncrementValueAction.prototype.serialize = function (parent) {
  53101. return _super.prototype._serialize.call(this, {
  53102. name: "IncrementValueAction",
  53103. properties: [
  53104. BABYLON.Action._GetTargetProperty(this._target),
  53105. { name: "propertyPath", value: this.propertyPath },
  53106. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53107. ]
  53108. }, parent);
  53109. };
  53110. return IncrementValueAction;
  53111. }(BABYLON.Action));
  53112. BABYLON.IncrementValueAction = IncrementValueAction;
  53113. var PlayAnimationAction = /** @class */ (function (_super) {
  53114. __extends(PlayAnimationAction, _super);
  53115. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53116. var _this = _super.call(this, triggerOptions, condition) || this;
  53117. _this.from = from;
  53118. _this.to = to;
  53119. _this.loop = loop;
  53120. _this._target = target;
  53121. return _this;
  53122. }
  53123. PlayAnimationAction.prototype._prepare = function () {
  53124. };
  53125. PlayAnimationAction.prototype.execute = function () {
  53126. var scene = this._actionManager.getScene();
  53127. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53128. };
  53129. PlayAnimationAction.prototype.serialize = function (parent) {
  53130. return _super.prototype._serialize.call(this, {
  53131. name: "PlayAnimationAction",
  53132. properties: [
  53133. BABYLON.Action._GetTargetProperty(this._target),
  53134. { name: "from", value: String(this.from) },
  53135. { name: "to", value: String(this.to) },
  53136. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53137. ]
  53138. }, parent);
  53139. };
  53140. return PlayAnimationAction;
  53141. }(BABYLON.Action));
  53142. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53143. var StopAnimationAction = /** @class */ (function (_super) {
  53144. __extends(StopAnimationAction, _super);
  53145. function StopAnimationAction(triggerOptions, target, condition) {
  53146. var _this = _super.call(this, triggerOptions, condition) || this;
  53147. _this._target = target;
  53148. return _this;
  53149. }
  53150. StopAnimationAction.prototype._prepare = function () {
  53151. };
  53152. StopAnimationAction.prototype.execute = function () {
  53153. var scene = this._actionManager.getScene();
  53154. scene.stopAnimation(this._target);
  53155. };
  53156. StopAnimationAction.prototype.serialize = function (parent) {
  53157. return _super.prototype._serialize.call(this, {
  53158. name: "StopAnimationAction",
  53159. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53160. }, parent);
  53161. };
  53162. return StopAnimationAction;
  53163. }(BABYLON.Action));
  53164. BABYLON.StopAnimationAction = StopAnimationAction;
  53165. var DoNothingAction = /** @class */ (function (_super) {
  53166. __extends(DoNothingAction, _super);
  53167. function DoNothingAction(triggerOptions, condition) {
  53168. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53169. return _super.call(this, triggerOptions, condition) || this;
  53170. }
  53171. DoNothingAction.prototype.execute = function () {
  53172. };
  53173. DoNothingAction.prototype.serialize = function (parent) {
  53174. return _super.prototype._serialize.call(this, {
  53175. name: "DoNothingAction",
  53176. properties: []
  53177. }, parent);
  53178. };
  53179. return DoNothingAction;
  53180. }(BABYLON.Action));
  53181. BABYLON.DoNothingAction = DoNothingAction;
  53182. var CombineAction = /** @class */ (function (_super) {
  53183. __extends(CombineAction, _super);
  53184. function CombineAction(triggerOptions, children, condition) {
  53185. var _this = _super.call(this, triggerOptions, condition) || this;
  53186. _this.children = children;
  53187. return _this;
  53188. }
  53189. CombineAction.prototype._prepare = function () {
  53190. for (var index = 0; index < this.children.length; index++) {
  53191. this.children[index]._actionManager = this._actionManager;
  53192. this.children[index]._prepare();
  53193. }
  53194. };
  53195. CombineAction.prototype.execute = function (evt) {
  53196. for (var index = 0; index < this.children.length; index++) {
  53197. this.children[index].execute(evt);
  53198. }
  53199. };
  53200. CombineAction.prototype.serialize = function (parent) {
  53201. var serializationObject = _super.prototype._serialize.call(this, {
  53202. name: "CombineAction",
  53203. properties: [],
  53204. combine: []
  53205. }, parent);
  53206. for (var i = 0; i < this.children.length; i++) {
  53207. serializationObject.combine.push(this.children[i].serialize(null));
  53208. }
  53209. return serializationObject;
  53210. };
  53211. return CombineAction;
  53212. }(BABYLON.Action));
  53213. BABYLON.CombineAction = CombineAction;
  53214. var ExecuteCodeAction = /** @class */ (function (_super) {
  53215. __extends(ExecuteCodeAction, _super);
  53216. function ExecuteCodeAction(triggerOptions, func, condition) {
  53217. var _this = _super.call(this, triggerOptions, condition) || this;
  53218. _this.func = func;
  53219. return _this;
  53220. }
  53221. ExecuteCodeAction.prototype.execute = function (evt) {
  53222. this.func(evt);
  53223. };
  53224. return ExecuteCodeAction;
  53225. }(BABYLON.Action));
  53226. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53227. var SetParentAction = /** @class */ (function (_super) {
  53228. __extends(SetParentAction, _super);
  53229. function SetParentAction(triggerOptions, target, parent, condition) {
  53230. var _this = _super.call(this, triggerOptions, condition) || this;
  53231. _this._target = target;
  53232. _this._parent = parent;
  53233. return _this;
  53234. }
  53235. SetParentAction.prototype._prepare = function () {
  53236. };
  53237. SetParentAction.prototype.execute = function () {
  53238. if (this._target.parent === this._parent) {
  53239. return;
  53240. }
  53241. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53242. invertParentWorldMatrix.invert();
  53243. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53244. this._target.parent = this._parent;
  53245. };
  53246. SetParentAction.prototype.serialize = function (parent) {
  53247. return _super.prototype._serialize.call(this, {
  53248. name: "SetParentAction",
  53249. properties: [
  53250. BABYLON.Action._GetTargetProperty(this._target),
  53251. BABYLON.Action._GetTargetProperty(this._parent),
  53252. ]
  53253. }, parent);
  53254. };
  53255. return SetParentAction;
  53256. }(BABYLON.Action));
  53257. BABYLON.SetParentAction = SetParentAction;
  53258. var PlaySoundAction = /** @class */ (function (_super) {
  53259. __extends(PlaySoundAction, _super);
  53260. function PlaySoundAction(triggerOptions, sound, condition) {
  53261. var _this = _super.call(this, triggerOptions, condition) || this;
  53262. _this._sound = sound;
  53263. return _this;
  53264. }
  53265. PlaySoundAction.prototype._prepare = function () {
  53266. };
  53267. PlaySoundAction.prototype.execute = function () {
  53268. if (this._sound !== undefined)
  53269. this._sound.play();
  53270. };
  53271. PlaySoundAction.prototype.serialize = function (parent) {
  53272. return _super.prototype._serialize.call(this, {
  53273. name: "PlaySoundAction",
  53274. properties: [{ name: "sound", value: this._sound.name }]
  53275. }, parent);
  53276. };
  53277. return PlaySoundAction;
  53278. }(BABYLON.Action));
  53279. BABYLON.PlaySoundAction = PlaySoundAction;
  53280. var StopSoundAction = /** @class */ (function (_super) {
  53281. __extends(StopSoundAction, _super);
  53282. function StopSoundAction(triggerOptions, sound, condition) {
  53283. var _this = _super.call(this, triggerOptions, condition) || this;
  53284. _this._sound = sound;
  53285. return _this;
  53286. }
  53287. StopSoundAction.prototype._prepare = function () {
  53288. };
  53289. StopSoundAction.prototype.execute = function () {
  53290. if (this._sound !== undefined)
  53291. this._sound.stop();
  53292. };
  53293. StopSoundAction.prototype.serialize = function (parent) {
  53294. return _super.prototype._serialize.call(this, {
  53295. name: "StopSoundAction",
  53296. properties: [{ name: "sound", value: this._sound.name }]
  53297. }, parent);
  53298. };
  53299. return StopSoundAction;
  53300. }(BABYLON.Action));
  53301. BABYLON.StopSoundAction = StopSoundAction;
  53302. })(BABYLON || (BABYLON = {}));
  53303. //# sourceMappingURL=babylon.directActions.js.map
  53304. var BABYLON;
  53305. (function (BABYLON) {
  53306. var SpriteManager = /** @class */ (function () {
  53307. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53308. if (epsilon === void 0) { epsilon = 0.01; }
  53309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53310. this.name = name;
  53311. this.sprites = new Array();
  53312. this.renderingGroupId = 0;
  53313. this.layerMask = 0x0FFFFFFF;
  53314. this.fogEnabled = true;
  53315. this.isPickable = false;
  53316. /**
  53317. * An event triggered when the manager is disposed.
  53318. */
  53319. this.onDisposeObservable = new BABYLON.Observable();
  53320. this._vertexBuffers = {};
  53321. this._capacity = capacity;
  53322. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53323. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53324. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53325. if (cellSize.width && cellSize.height) {
  53326. this.cellWidth = cellSize.width;
  53327. this.cellHeight = cellSize.height;
  53328. }
  53329. else if (cellSize !== undefined) {
  53330. this.cellWidth = cellSize;
  53331. this.cellHeight = cellSize;
  53332. }
  53333. else {
  53334. return;
  53335. }
  53336. this._epsilon = epsilon;
  53337. this._scene = scene;
  53338. this._scene.spriteManagers.push(this);
  53339. var indices = [];
  53340. var index = 0;
  53341. for (var count = 0; count < capacity; count++) {
  53342. indices.push(index);
  53343. indices.push(index + 1);
  53344. indices.push(index + 2);
  53345. indices.push(index);
  53346. indices.push(index + 2);
  53347. indices.push(index + 3);
  53348. index += 4;
  53349. }
  53350. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53351. // VBO
  53352. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53353. this._vertexData = new Float32Array(capacity * 16 * 4);
  53354. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53355. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53356. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53357. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53358. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53359. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53360. this._vertexBuffers["options"] = options;
  53361. this._vertexBuffers["cellInfo"] = cellInfo;
  53362. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53363. // Effects
  53364. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53365. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53366. }
  53367. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53368. set: function (callback) {
  53369. if (this._onDisposeObserver) {
  53370. this.onDisposeObservable.remove(this._onDisposeObserver);
  53371. }
  53372. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53373. },
  53374. enumerable: true,
  53375. configurable: true
  53376. });
  53377. Object.defineProperty(SpriteManager.prototype, "texture", {
  53378. get: function () {
  53379. return this._spriteTexture;
  53380. },
  53381. set: function (value) {
  53382. this._spriteTexture = value;
  53383. },
  53384. enumerable: true,
  53385. configurable: true
  53386. });
  53387. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53388. var arrayOffset = index * 16;
  53389. if (offsetX === 0)
  53390. offsetX = this._epsilon;
  53391. else if (offsetX === 1)
  53392. offsetX = 1 - this._epsilon;
  53393. if (offsetY === 0)
  53394. offsetY = this._epsilon;
  53395. else if (offsetY === 1)
  53396. offsetY = 1 - this._epsilon;
  53397. this._vertexData[arrayOffset] = sprite.position.x;
  53398. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53399. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53400. this._vertexData[arrayOffset + 3] = sprite.angle;
  53401. this._vertexData[arrayOffset + 4] = sprite.width;
  53402. this._vertexData[arrayOffset + 5] = sprite.height;
  53403. this._vertexData[arrayOffset + 6] = offsetX;
  53404. this._vertexData[arrayOffset + 7] = offsetY;
  53405. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53406. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53407. var offset = (sprite.cellIndex / rowSize) >> 0;
  53408. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53409. this._vertexData[arrayOffset + 11] = offset;
  53410. // Color
  53411. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53412. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53413. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53414. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53415. };
  53416. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53417. var count = Math.min(this._capacity, this.sprites.length);
  53418. var min = BABYLON.Vector3.Zero();
  53419. var max = BABYLON.Vector3.Zero();
  53420. var distance = Number.MAX_VALUE;
  53421. var currentSprite = null;
  53422. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53423. var cameraView = camera.getViewMatrix();
  53424. for (var index = 0; index < count; index++) {
  53425. var sprite = this.sprites[index];
  53426. if (!sprite) {
  53427. continue;
  53428. }
  53429. if (predicate) {
  53430. if (!predicate(sprite)) {
  53431. continue;
  53432. }
  53433. }
  53434. else if (!sprite.isPickable) {
  53435. continue;
  53436. }
  53437. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53438. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53439. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53440. if (ray.intersectsBoxMinMax(min, max)) {
  53441. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53442. if (distance > currentDistance) {
  53443. distance = currentDistance;
  53444. currentSprite = sprite;
  53445. if (fastCheck) {
  53446. break;
  53447. }
  53448. }
  53449. }
  53450. }
  53451. if (currentSprite) {
  53452. var result = new BABYLON.PickingInfo();
  53453. result.hit = true;
  53454. result.pickedSprite = currentSprite;
  53455. result.distance = distance;
  53456. return result;
  53457. }
  53458. return null;
  53459. };
  53460. SpriteManager.prototype.render = function () {
  53461. // Check
  53462. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53463. return;
  53464. var engine = this._scene.getEngine();
  53465. var baseSize = this._spriteTexture.getBaseSize();
  53466. // Sprites
  53467. var deltaTime = engine.getDeltaTime();
  53468. var max = Math.min(this._capacity, this.sprites.length);
  53469. var rowSize = baseSize.width / this.cellWidth;
  53470. var offset = 0;
  53471. for (var index = 0; index < max; index++) {
  53472. var sprite = this.sprites[index];
  53473. if (!sprite || !sprite.isVisible) {
  53474. continue;
  53475. }
  53476. sprite._animate(deltaTime);
  53477. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53478. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53479. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53480. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53481. }
  53482. this._buffer.update(this._vertexData);
  53483. // Render
  53484. var effect = this._effectBase;
  53485. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53486. effect = this._effectFog;
  53487. }
  53488. engine.enableEffect(effect);
  53489. var viewMatrix = this._scene.getViewMatrix();
  53490. effect.setTexture("diffuseSampler", this._spriteTexture);
  53491. effect.setMatrix("view", viewMatrix);
  53492. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53493. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53494. // Fog
  53495. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53496. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53497. effect.setColor3("vFogColor", this._scene.fogColor);
  53498. }
  53499. // VBOs
  53500. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53501. // Draw order
  53502. engine.setDepthFunctionToLessOrEqual();
  53503. effect.setBool("alphaTest", true);
  53504. engine.setColorWrite(false);
  53505. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53506. engine.setColorWrite(true);
  53507. effect.setBool("alphaTest", false);
  53508. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53509. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53510. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53511. };
  53512. SpriteManager.prototype.dispose = function () {
  53513. if (this._buffer) {
  53514. this._buffer.dispose();
  53515. this._buffer = null;
  53516. }
  53517. if (this._indexBuffer) {
  53518. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53519. this._indexBuffer = null;
  53520. }
  53521. if (this._spriteTexture) {
  53522. this._spriteTexture.dispose();
  53523. this._spriteTexture = null;
  53524. }
  53525. // Remove from scene
  53526. var index = this._scene.spriteManagers.indexOf(this);
  53527. this._scene.spriteManagers.splice(index, 1);
  53528. // Callback
  53529. this.onDisposeObservable.notifyObservers(this);
  53530. this.onDisposeObservable.clear();
  53531. };
  53532. return SpriteManager;
  53533. }());
  53534. BABYLON.SpriteManager = SpriteManager;
  53535. })(BABYLON || (BABYLON = {}));
  53536. //# sourceMappingURL=babylon.spriteManager.js.map
  53537. var BABYLON;
  53538. (function (BABYLON) {
  53539. var Sprite = /** @class */ (function () {
  53540. function Sprite(name, manager) {
  53541. this.name = name;
  53542. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53543. this.width = 1.0;
  53544. this.height = 1.0;
  53545. this.angle = 0;
  53546. this.cellIndex = 0;
  53547. this.invertU = 0;
  53548. this.invertV = 0;
  53549. this.animations = new Array();
  53550. this.isPickable = false;
  53551. this._animationStarted = false;
  53552. this._loopAnimation = false;
  53553. this._fromIndex = 0;
  53554. this._toIndex = 0;
  53555. this._delay = 0;
  53556. this._direction = 1;
  53557. this._time = 0;
  53558. /**
  53559. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53560. */
  53561. this.isVisible = true;
  53562. this._manager = manager;
  53563. this._manager.sprites.push(this);
  53564. this.position = BABYLON.Vector3.Zero();
  53565. }
  53566. Object.defineProperty(Sprite.prototype, "size", {
  53567. get: function () {
  53568. return this.width;
  53569. },
  53570. set: function (value) {
  53571. this.width = value;
  53572. this.height = value;
  53573. },
  53574. enumerable: true,
  53575. configurable: true
  53576. });
  53577. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53578. this._fromIndex = from;
  53579. this._toIndex = to;
  53580. this._loopAnimation = loop;
  53581. this._delay = delay;
  53582. this._animationStarted = true;
  53583. this._direction = from < to ? 1 : -1;
  53584. this.cellIndex = from;
  53585. this._time = 0;
  53586. this._onAnimationEnd = onAnimationEnd;
  53587. };
  53588. Sprite.prototype.stopAnimation = function () {
  53589. this._animationStarted = false;
  53590. };
  53591. Sprite.prototype._animate = function (deltaTime) {
  53592. if (!this._animationStarted)
  53593. return;
  53594. this._time += deltaTime;
  53595. if (this._time > this._delay) {
  53596. this._time = this._time % this._delay;
  53597. this.cellIndex += this._direction;
  53598. if (this.cellIndex > this._toIndex) {
  53599. if (this._loopAnimation) {
  53600. this.cellIndex = this._fromIndex;
  53601. }
  53602. else {
  53603. this.cellIndex = this._toIndex;
  53604. this._animationStarted = false;
  53605. if (this._onAnimationEnd) {
  53606. this._onAnimationEnd();
  53607. }
  53608. if (this.disposeWhenFinishedAnimating) {
  53609. this.dispose();
  53610. }
  53611. }
  53612. }
  53613. }
  53614. };
  53615. Sprite.prototype.dispose = function () {
  53616. for (var i = 0; i < this._manager.sprites.length; i++) {
  53617. if (this._manager.sprites[i] == this) {
  53618. this._manager.sprites.splice(i, 1);
  53619. }
  53620. }
  53621. };
  53622. return Sprite;
  53623. }());
  53624. BABYLON.Sprite = Sprite;
  53625. })(BABYLON || (BABYLON = {}));
  53626. //# sourceMappingURL=babylon.sprite.js.map
  53627. var BABYLON;
  53628. (function (BABYLON) {
  53629. var IntersectionInfo = /** @class */ (function () {
  53630. function IntersectionInfo(bu, bv, distance) {
  53631. this.bu = bu;
  53632. this.bv = bv;
  53633. this.distance = distance;
  53634. this.faceId = 0;
  53635. this.subMeshId = 0;
  53636. }
  53637. return IntersectionInfo;
  53638. }());
  53639. BABYLON.IntersectionInfo = IntersectionInfo;
  53640. /**
  53641. * Information about the result of picking within a scene
  53642. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53643. */
  53644. var PickingInfo = /** @class */ (function () {
  53645. function PickingInfo() {
  53646. /**
  53647. * If the pick collided with an object
  53648. */
  53649. this.hit = false;
  53650. /**
  53651. * Distance away where the pick collided
  53652. */
  53653. this.distance = 0;
  53654. /**
  53655. * The location of pick collision
  53656. */
  53657. this.pickedPoint = null;
  53658. /**
  53659. * The mesh corrisponding the the pick collision
  53660. */
  53661. this.pickedMesh = null;
  53662. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53663. this.bu = 0;
  53664. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53665. this.bv = 0;
  53666. /** The id of the face on the mesh that was picked */
  53667. this.faceId = -1;
  53668. /** Id of the the submesh that was picked */
  53669. this.subMeshId = 0;
  53670. /** If a sprite was picked, this will be the sprite the pick collided with */
  53671. this.pickedSprite = null;
  53672. /**
  53673. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53674. */
  53675. this.originMesh = null;
  53676. /**
  53677. * The ray that was used to perform the picking.
  53678. */
  53679. this.ray = null;
  53680. }
  53681. /**
  53682. * Gets the normal corrispodning to the face the pick collided with
  53683. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53684. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53685. * @returns The normal corrispodning to the face the pick collided with
  53686. */
  53687. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53688. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53689. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53690. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53691. return null;
  53692. }
  53693. var indices = this.pickedMesh.getIndices();
  53694. if (!indices) {
  53695. return null;
  53696. }
  53697. var result;
  53698. if (useVerticesNormals) {
  53699. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53700. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53701. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53702. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53703. normal0 = normal0.scale(this.bu);
  53704. normal1 = normal1.scale(this.bv);
  53705. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53706. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53707. }
  53708. else {
  53709. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53710. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53711. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53712. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53713. var p1p2 = vertex1.subtract(vertex2);
  53714. var p3p2 = vertex3.subtract(vertex2);
  53715. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53716. }
  53717. if (useWorldCoordinates) {
  53718. var wm = this.pickedMesh.getWorldMatrix();
  53719. if (this.pickedMesh.nonUniformScaling) {
  53720. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53721. wm = BABYLON.Tmp.Matrix[0];
  53722. wm.setTranslationFromFloats(0, 0, 0);
  53723. wm.invert();
  53724. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53725. wm = BABYLON.Tmp.Matrix[1];
  53726. }
  53727. result = BABYLON.Vector3.TransformNormal(result, wm);
  53728. }
  53729. result.normalize();
  53730. return result;
  53731. };
  53732. /**
  53733. * Gets the texture coordinates of where the pick occured
  53734. * @returns the vector containing the coordnates of the texture
  53735. */
  53736. PickingInfo.prototype.getTextureCoordinates = function () {
  53737. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53738. return null;
  53739. }
  53740. var indices = this.pickedMesh.getIndices();
  53741. if (!indices) {
  53742. return null;
  53743. }
  53744. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53745. if (!uvs) {
  53746. return null;
  53747. }
  53748. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53749. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53750. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53751. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53752. uv1 = uv1.scale(this.bu);
  53753. uv2 = uv2.scale(this.bv);
  53754. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53755. };
  53756. return PickingInfo;
  53757. }());
  53758. BABYLON.PickingInfo = PickingInfo;
  53759. })(BABYLON || (BABYLON = {}));
  53760. //# sourceMappingURL=babylon.pickingInfo.js.map
  53761. var BABYLON;
  53762. (function (BABYLON) {
  53763. var Ray = /** @class */ (function () {
  53764. function Ray(origin, direction, length) {
  53765. if (length === void 0) { length = Number.MAX_VALUE; }
  53766. this.origin = origin;
  53767. this.direction = direction;
  53768. this.length = length;
  53769. }
  53770. // Methods
  53771. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53772. var d = 0.0;
  53773. var maxValue = Number.MAX_VALUE;
  53774. var inv;
  53775. var min;
  53776. var max;
  53777. var temp;
  53778. if (Math.abs(this.direction.x) < 0.0000001) {
  53779. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53780. return false;
  53781. }
  53782. }
  53783. else {
  53784. inv = 1.0 / this.direction.x;
  53785. min = (minimum.x - this.origin.x) * inv;
  53786. max = (maximum.x - this.origin.x) * inv;
  53787. if (max === -Infinity) {
  53788. max = Infinity;
  53789. }
  53790. if (min > max) {
  53791. temp = min;
  53792. min = max;
  53793. max = temp;
  53794. }
  53795. d = Math.max(min, d);
  53796. maxValue = Math.min(max, maxValue);
  53797. if (d > maxValue) {
  53798. return false;
  53799. }
  53800. }
  53801. if (Math.abs(this.direction.y) < 0.0000001) {
  53802. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53803. return false;
  53804. }
  53805. }
  53806. else {
  53807. inv = 1.0 / this.direction.y;
  53808. min = (minimum.y - this.origin.y) * inv;
  53809. max = (maximum.y - this.origin.y) * inv;
  53810. if (max === -Infinity) {
  53811. max = Infinity;
  53812. }
  53813. if (min > max) {
  53814. temp = min;
  53815. min = max;
  53816. max = temp;
  53817. }
  53818. d = Math.max(min, d);
  53819. maxValue = Math.min(max, maxValue);
  53820. if (d > maxValue) {
  53821. return false;
  53822. }
  53823. }
  53824. if (Math.abs(this.direction.z) < 0.0000001) {
  53825. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53826. return false;
  53827. }
  53828. }
  53829. else {
  53830. inv = 1.0 / this.direction.z;
  53831. min = (minimum.z - this.origin.z) * inv;
  53832. max = (maximum.z - this.origin.z) * inv;
  53833. if (max === -Infinity) {
  53834. max = Infinity;
  53835. }
  53836. if (min > max) {
  53837. temp = min;
  53838. min = max;
  53839. max = temp;
  53840. }
  53841. d = Math.max(min, d);
  53842. maxValue = Math.min(max, maxValue);
  53843. if (d > maxValue) {
  53844. return false;
  53845. }
  53846. }
  53847. return true;
  53848. };
  53849. Ray.prototype.intersectsBox = function (box) {
  53850. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53851. };
  53852. Ray.prototype.intersectsSphere = function (sphere) {
  53853. var x = sphere.center.x - this.origin.x;
  53854. var y = sphere.center.y - this.origin.y;
  53855. var z = sphere.center.z - this.origin.z;
  53856. var pyth = (x * x) + (y * y) + (z * z);
  53857. var rr = sphere.radius * sphere.radius;
  53858. if (pyth <= rr) {
  53859. return true;
  53860. }
  53861. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53862. if (dot < 0.0) {
  53863. return false;
  53864. }
  53865. var temp = pyth - (dot * dot);
  53866. return temp <= rr;
  53867. };
  53868. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53869. if (!this._edge1) {
  53870. this._edge1 = BABYLON.Vector3.Zero();
  53871. this._edge2 = BABYLON.Vector3.Zero();
  53872. this._pvec = BABYLON.Vector3.Zero();
  53873. this._tvec = BABYLON.Vector3.Zero();
  53874. this._qvec = BABYLON.Vector3.Zero();
  53875. }
  53876. vertex1.subtractToRef(vertex0, this._edge1);
  53877. vertex2.subtractToRef(vertex0, this._edge2);
  53878. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53879. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53880. if (det === 0) {
  53881. return null;
  53882. }
  53883. var invdet = 1 / det;
  53884. this.origin.subtractToRef(vertex0, this._tvec);
  53885. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53886. if (bu < 0 || bu > 1.0) {
  53887. return null;
  53888. }
  53889. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53890. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53891. if (bv < 0 || bu + bv > 1.0) {
  53892. return null;
  53893. }
  53894. //check if the distance is longer than the predefined length.
  53895. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53896. if (distance > this.length) {
  53897. return null;
  53898. }
  53899. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53900. };
  53901. Ray.prototype.intersectsPlane = function (plane) {
  53902. var distance;
  53903. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53904. if (Math.abs(result1) < 9.99999997475243E-07) {
  53905. return null;
  53906. }
  53907. else {
  53908. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53909. distance = (-plane.d - result2) / result1;
  53910. if (distance < 0.0) {
  53911. if (distance < -9.99999997475243E-07) {
  53912. return null;
  53913. }
  53914. else {
  53915. return 0;
  53916. }
  53917. }
  53918. return distance;
  53919. }
  53920. };
  53921. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53922. var tm = BABYLON.Tmp.Matrix[0];
  53923. mesh.getWorldMatrix().invertToRef(tm);
  53924. if (this._tmpRay) {
  53925. Ray.TransformToRef(this, tm, this._tmpRay);
  53926. }
  53927. else {
  53928. this._tmpRay = Ray.Transform(this, tm);
  53929. }
  53930. return mesh.intersects(this._tmpRay, fastCheck);
  53931. };
  53932. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53933. if (results) {
  53934. results.length = 0;
  53935. }
  53936. else {
  53937. results = [];
  53938. }
  53939. for (var i = 0; i < meshes.length; i++) {
  53940. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53941. if (pickInfo.hit) {
  53942. results.push(pickInfo);
  53943. }
  53944. }
  53945. results.sort(this._comparePickingInfo);
  53946. return results;
  53947. };
  53948. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53949. if (pickingInfoA.distance < pickingInfoB.distance) {
  53950. return -1;
  53951. }
  53952. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53953. return 1;
  53954. }
  53955. else {
  53956. return 0;
  53957. }
  53958. };
  53959. /**
  53960. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53961. * @param sega the first point of the segment to test the intersection against
  53962. * @param segb the second point of the segment to test the intersection against
  53963. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53964. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53965. */
  53966. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53967. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53968. var u = segb.subtract(sega);
  53969. var v = rsegb.subtract(this.origin);
  53970. var w = sega.subtract(this.origin);
  53971. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53972. var b = BABYLON.Vector3.Dot(u, v);
  53973. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53974. var d = BABYLON.Vector3.Dot(u, w);
  53975. var e = BABYLON.Vector3.Dot(v, w);
  53976. var D = a * c - b * b; // always >= 0
  53977. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53978. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53979. // compute the line parameters of the two closest points
  53980. if (D < Ray.smallnum) { // the lines are almost parallel
  53981. sN = 0.0; // force using point P0 on segment S1
  53982. sD = 1.0; // to prevent possible division by 0.0 later
  53983. tN = e;
  53984. tD = c;
  53985. }
  53986. else { // get the closest points on the infinite lines
  53987. sN = (b * e - c * d);
  53988. tN = (a * e - b * d);
  53989. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  53990. sN = 0.0;
  53991. tN = e;
  53992. tD = c;
  53993. }
  53994. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  53995. sN = sD;
  53996. tN = e + b;
  53997. tD = c;
  53998. }
  53999. }
  54000. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54001. tN = 0.0;
  54002. // recompute sc for this edge
  54003. if (-d < 0.0) {
  54004. sN = 0.0;
  54005. }
  54006. else if (-d > a)
  54007. sN = sD;
  54008. else {
  54009. sN = -d;
  54010. sD = a;
  54011. }
  54012. }
  54013. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54014. tN = tD;
  54015. // recompute sc for this edge
  54016. if ((-d + b) < 0.0) {
  54017. sN = 0;
  54018. }
  54019. else if ((-d + b) > a) {
  54020. sN = sD;
  54021. }
  54022. else {
  54023. sN = (-d + b);
  54024. sD = a;
  54025. }
  54026. }
  54027. // finally do the division to get sc and tc
  54028. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54029. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54030. // get the difference of the two closest points
  54031. var qtc = v.multiplyByFloats(tc, tc, tc);
  54032. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54033. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54034. if (isIntersected) {
  54035. return qtc.length();
  54036. }
  54037. return -1;
  54038. };
  54039. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54040. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54041. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54042. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54043. this.direction.normalize();
  54044. return this;
  54045. };
  54046. // Statics
  54047. Ray.Zero = function () {
  54048. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54049. };
  54050. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54051. var result = Ray.Zero();
  54052. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54053. };
  54054. /**
  54055. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  54056. * transformed to the given world matrix.
  54057. * @param origin The origin point
  54058. * @param end The end point
  54059. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54060. */
  54061. Ray.CreateNewFromTo = function (origin, end, world) {
  54062. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54063. var direction = end.subtract(origin);
  54064. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54065. direction.normalize();
  54066. return Ray.Transform(new Ray(origin, direction, length), world);
  54067. };
  54068. Ray.Transform = function (ray, matrix) {
  54069. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54070. Ray.TransformToRef(ray, matrix, result);
  54071. return result;
  54072. };
  54073. Ray.TransformToRef = function (ray, matrix, result) {
  54074. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54075. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54076. result.length = ray.length;
  54077. var dir = result.direction;
  54078. var len = dir.length();
  54079. if (!(len === 0 || len === 1)) {
  54080. var num = 1.0 / len;
  54081. dir.x *= num;
  54082. dir.y *= num;
  54083. dir.z *= num;
  54084. result.length *= len;
  54085. }
  54086. };
  54087. Ray.smallnum = 0.00000001;
  54088. Ray.rayl = 10e8;
  54089. return Ray;
  54090. }());
  54091. BABYLON.Ray = Ray;
  54092. })(BABYLON || (BABYLON = {}));
  54093. //# sourceMappingURL=babylon.ray.js.map
  54094. var BABYLON;
  54095. (function (BABYLON) {
  54096. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54097. if (boxMin.x > sphereCenter.x + sphereRadius)
  54098. return false;
  54099. if (sphereCenter.x - sphereRadius > boxMax.x)
  54100. return false;
  54101. if (boxMin.y > sphereCenter.y + sphereRadius)
  54102. return false;
  54103. if (sphereCenter.y - sphereRadius > boxMax.y)
  54104. return false;
  54105. if (boxMin.z > sphereCenter.z + sphereRadius)
  54106. return false;
  54107. if (sphereCenter.z - sphereRadius > boxMax.z)
  54108. return false;
  54109. return true;
  54110. };
  54111. var getLowestRoot = (function () {
  54112. var result = { root: 0, found: false };
  54113. return function (a, b, c, maxR) {
  54114. result.root = 0;
  54115. result.found = false;
  54116. var determinant = b * b - 4.0 * a * c;
  54117. if (determinant < 0)
  54118. return result;
  54119. var sqrtD = Math.sqrt(determinant);
  54120. var r1 = (-b - sqrtD) / (2.0 * a);
  54121. var r2 = (-b + sqrtD) / (2.0 * a);
  54122. if (r1 > r2) {
  54123. var temp = r2;
  54124. r2 = r1;
  54125. r1 = temp;
  54126. }
  54127. if (r1 > 0 && r1 < maxR) {
  54128. result.root = r1;
  54129. result.found = true;
  54130. return result;
  54131. }
  54132. if (r2 > 0 && r2 < maxR) {
  54133. result.root = r2;
  54134. result.found = true;
  54135. return result;
  54136. }
  54137. return result;
  54138. };
  54139. })();
  54140. var Collider = /** @class */ (function () {
  54141. function Collider() {
  54142. this._collisionPoint = BABYLON.Vector3.Zero();
  54143. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54144. this._tempVector = BABYLON.Vector3.Zero();
  54145. this._tempVector2 = BABYLON.Vector3.Zero();
  54146. this._tempVector3 = BABYLON.Vector3.Zero();
  54147. this._tempVector4 = BABYLON.Vector3.Zero();
  54148. this._edge = BABYLON.Vector3.Zero();
  54149. this._baseToVertex = BABYLON.Vector3.Zero();
  54150. this._destinationPoint = BABYLON.Vector3.Zero();
  54151. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54152. this._displacementVector = BABYLON.Vector3.Zero();
  54153. this._radius = BABYLON.Vector3.One();
  54154. this._retry = 0;
  54155. this._basePointWorld = BABYLON.Vector3.Zero();
  54156. this._velocityWorld = BABYLON.Vector3.Zero();
  54157. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54158. this._collisionMask = -1;
  54159. }
  54160. Object.defineProperty(Collider.prototype, "collisionMask", {
  54161. get: function () {
  54162. return this._collisionMask;
  54163. },
  54164. set: function (mask) {
  54165. this._collisionMask = !isNaN(mask) ? mask : -1;
  54166. },
  54167. enumerable: true,
  54168. configurable: true
  54169. });
  54170. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54171. /**
  54172. * Gets the plane normal used to compute the sliding response (in local space)
  54173. */
  54174. get: function () {
  54175. return this._slidePlaneNormal;
  54176. },
  54177. enumerable: true,
  54178. configurable: true
  54179. });
  54180. // Methods
  54181. Collider.prototype._initialize = function (source, dir, e) {
  54182. this._velocity = dir;
  54183. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54184. this._basePoint = source;
  54185. source.multiplyToRef(this._radius, this._basePointWorld);
  54186. dir.multiplyToRef(this._radius, this._velocityWorld);
  54187. this._velocityWorldLength = this._velocityWorld.length();
  54188. this._epsilon = e;
  54189. this.collisionFound = false;
  54190. };
  54191. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54192. pa.subtractToRef(point, this._tempVector);
  54193. pb.subtractToRef(point, this._tempVector2);
  54194. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54195. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54196. if (d < 0)
  54197. return false;
  54198. pc.subtractToRef(point, this._tempVector3);
  54199. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54200. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54201. if (d < 0)
  54202. return false;
  54203. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54204. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54205. return d >= 0;
  54206. };
  54207. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54208. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54209. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54210. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54211. return false;
  54212. }
  54213. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54214. return false;
  54215. return true;
  54216. };
  54217. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54218. var t0;
  54219. var embeddedInPlane = false;
  54220. //defensive programming, actually not needed.
  54221. if (!trianglePlaneArray) {
  54222. trianglePlaneArray = [];
  54223. }
  54224. if (!trianglePlaneArray[faceIndex]) {
  54225. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54226. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54227. }
  54228. var trianglePlane = trianglePlaneArray[faceIndex];
  54229. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54230. return;
  54231. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54232. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54233. if (normalDotVelocity == 0) {
  54234. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54235. return;
  54236. embeddedInPlane = true;
  54237. t0 = 0;
  54238. }
  54239. else {
  54240. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54241. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54242. if (t0 > t1) {
  54243. var temp = t1;
  54244. t1 = t0;
  54245. t0 = temp;
  54246. }
  54247. if (t0 > 1.0 || t1 < 0.0)
  54248. return;
  54249. if (t0 < 0)
  54250. t0 = 0;
  54251. if (t0 > 1.0)
  54252. t0 = 1.0;
  54253. }
  54254. this._collisionPoint.copyFromFloats(0, 0, 0);
  54255. var found = false;
  54256. var t = 1.0;
  54257. if (!embeddedInPlane) {
  54258. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54259. this._velocity.scaleToRef(t0, this._tempVector);
  54260. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54261. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54262. found = true;
  54263. t = t0;
  54264. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54265. }
  54266. }
  54267. if (!found) {
  54268. var velocitySquaredLength = this._velocity.lengthSquared();
  54269. var a = velocitySquaredLength;
  54270. this._basePoint.subtractToRef(p1, this._tempVector);
  54271. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54272. var c = this._tempVector.lengthSquared() - 1.0;
  54273. var lowestRoot = getLowestRoot(a, b, c, t);
  54274. if (lowestRoot.found) {
  54275. t = lowestRoot.root;
  54276. found = true;
  54277. this._collisionPoint.copyFrom(p1);
  54278. }
  54279. this._basePoint.subtractToRef(p2, this._tempVector);
  54280. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54281. c = this._tempVector.lengthSquared() - 1.0;
  54282. lowestRoot = getLowestRoot(a, b, c, t);
  54283. if (lowestRoot.found) {
  54284. t = lowestRoot.root;
  54285. found = true;
  54286. this._collisionPoint.copyFrom(p2);
  54287. }
  54288. this._basePoint.subtractToRef(p3, this._tempVector);
  54289. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54290. c = this._tempVector.lengthSquared() - 1.0;
  54291. lowestRoot = getLowestRoot(a, b, c, t);
  54292. if (lowestRoot.found) {
  54293. t = lowestRoot.root;
  54294. found = true;
  54295. this._collisionPoint.copyFrom(p3);
  54296. }
  54297. p2.subtractToRef(p1, this._edge);
  54298. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54299. var edgeSquaredLength = this._edge.lengthSquared();
  54300. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54301. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54302. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54303. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54304. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54305. lowestRoot = getLowestRoot(a, b, c, t);
  54306. if (lowestRoot.found) {
  54307. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54308. if (f >= 0.0 && f <= 1.0) {
  54309. t = lowestRoot.root;
  54310. found = true;
  54311. this._edge.scaleInPlace(f);
  54312. p1.addToRef(this._edge, this._collisionPoint);
  54313. }
  54314. }
  54315. p3.subtractToRef(p2, this._edge);
  54316. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54317. edgeSquaredLength = this._edge.lengthSquared();
  54318. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54319. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54320. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54321. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54322. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54323. lowestRoot = getLowestRoot(a, b, c, t);
  54324. if (lowestRoot.found) {
  54325. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54326. if (f >= 0.0 && f <= 1.0) {
  54327. t = lowestRoot.root;
  54328. found = true;
  54329. this._edge.scaleInPlace(f);
  54330. p2.addToRef(this._edge, this._collisionPoint);
  54331. }
  54332. }
  54333. p1.subtractToRef(p3, this._edge);
  54334. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54335. edgeSquaredLength = this._edge.lengthSquared();
  54336. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54337. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54338. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54339. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54340. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54341. lowestRoot = getLowestRoot(a, b, c, t);
  54342. if (lowestRoot.found) {
  54343. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54344. if (f >= 0.0 && f <= 1.0) {
  54345. t = lowestRoot.root;
  54346. found = true;
  54347. this._edge.scaleInPlace(f);
  54348. p3.addToRef(this._edge, this._collisionPoint);
  54349. }
  54350. }
  54351. }
  54352. if (found) {
  54353. var distToCollision = t * this._velocity.length();
  54354. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54355. if (!this.intersectionPoint) {
  54356. this.intersectionPoint = this._collisionPoint.clone();
  54357. }
  54358. else {
  54359. this.intersectionPoint.copyFrom(this._collisionPoint);
  54360. }
  54361. this._nearestDistance = distToCollision;
  54362. this.collisionFound = true;
  54363. }
  54364. }
  54365. };
  54366. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54367. for (var i = indexStart; i < indexEnd; i += 3) {
  54368. var p1 = pts[indices[i] - decal];
  54369. var p2 = pts[indices[i + 1] - decal];
  54370. var p3 = pts[indices[i + 2] - decal];
  54371. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54372. }
  54373. };
  54374. Collider.prototype._getResponse = function (pos, vel) {
  54375. pos.addToRef(vel, this._destinationPoint);
  54376. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54377. this._basePoint.addToRef(vel, pos);
  54378. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54379. this._slidePlaneNormal.normalize();
  54380. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54381. pos.addInPlace(this._displacementVector);
  54382. this.intersectionPoint.addInPlace(this._displacementVector);
  54383. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54384. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54385. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54386. };
  54387. return Collider;
  54388. }());
  54389. BABYLON.Collider = Collider;
  54390. })(BABYLON || (BABYLON = {}));
  54391. //# sourceMappingURL=babylon.collider.js.map
  54392. var BABYLON;
  54393. (function (BABYLON) {
  54394. //WebWorker code will be inserted to this variable.
  54395. BABYLON.CollisionWorker = "";
  54396. /** Defines supported task for worker process */
  54397. var WorkerTaskType;
  54398. (function (WorkerTaskType) {
  54399. /** Initialization */
  54400. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54401. /** Update of geometry */
  54402. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54403. /** Evaluate collision */
  54404. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54405. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54406. /** Defines kind of replies returned by worker */
  54407. var WorkerReplyType;
  54408. (function (WorkerReplyType) {
  54409. /** Success */
  54410. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54411. /** Unkown error */
  54412. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54413. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54414. var CollisionCoordinatorWorker = /** @class */ (function () {
  54415. function CollisionCoordinatorWorker() {
  54416. var _this = this;
  54417. this._scaledPosition = BABYLON.Vector3.Zero();
  54418. this._scaledVelocity = BABYLON.Vector3.Zero();
  54419. this.onMeshUpdated = function (transformNode) {
  54420. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54421. };
  54422. this.onGeometryUpdated = function (geometry) {
  54423. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54424. };
  54425. this._afterRender = function () {
  54426. if (!_this._init)
  54427. return;
  54428. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54429. return;
  54430. }
  54431. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54432. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54433. if (_this._runningUpdated > 4) {
  54434. return;
  54435. }
  54436. ++_this._runningUpdated;
  54437. var payload = {
  54438. updatedMeshes: _this._addUpdateMeshesList,
  54439. updatedGeometries: _this._addUpdateGeometriesList,
  54440. removedGeometries: _this._toRemoveGeometryArray,
  54441. removedMeshes: _this._toRemoveMeshesArray
  54442. };
  54443. var message = {
  54444. payload: payload,
  54445. taskType: WorkerTaskType.UPDATE
  54446. };
  54447. var serializable = [];
  54448. for (var id in payload.updatedGeometries) {
  54449. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54450. //prepare transferables
  54451. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54452. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54453. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54454. }
  54455. }
  54456. _this._worker.postMessage(message, serializable);
  54457. _this._addUpdateMeshesList = {};
  54458. _this._addUpdateGeometriesList = {};
  54459. _this._toRemoveGeometryArray = [];
  54460. _this._toRemoveMeshesArray = [];
  54461. };
  54462. this._onMessageFromWorker = function (e) {
  54463. var returnData = e.data;
  54464. if (returnData.error != WorkerReplyType.SUCCESS) {
  54465. //TODO what errors can be returned from the worker?
  54466. BABYLON.Tools.Warn("error returned from worker!");
  54467. return;
  54468. }
  54469. switch (returnData.taskType) {
  54470. case WorkerTaskType.INIT:
  54471. _this._init = true;
  54472. //Update the worked with ALL of the scene's current state
  54473. _this._scene.meshes.forEach(function (mesh) {
  54474. _this.onMeshAdded(mesh);
  54475. });
  54476. _this._scene.getGeometries().forEach(function (geometry) {
  54477. _this.onGeometryAdded(geometry);
  54478. });
  54479. break;
  54480. case WorkerTaskType.UPDATE:
  54481. _this._runningUpdated--;
  54482. break;
  54483. case WorkerTaskType.COLLIDE:
  54484. var returnPayload = returnData.payload;
  54485. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54486. return;
  54487. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54488. if (callback) {
  54489. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54490. if (mesh) {
  54491. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54492. }
  54493. }
  54494. //cleanup
  54495. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54496. break;
  54497. }
  54498. };
  54499. this._collisionsCallbackArray = [];
  54500. this._init = false;
  54501. this._runningUpdated = 0;
  54502. this._addUpdateMeshesList = {};
  54503. this._addUpdateGeometriesList = {};
  54504. this._toRemoveGeometryArray = [];
  54505. this._toRemoveMeshesArray = [];
  54506. }
  54507. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54508. if (!this._init)
  54509. return;
  54510. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54511. return;
  54512. position.divideToRef(collider._radius, this._scaledPosition);
  54513. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54514. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54515. var payload = {
  54516. collider: {
  54517. position: this._scaledPosition.asArray(),
  54518. velocity: this._scaledVelocity.asArray(),
  54519. radius: collider._radius.asArray()
  54520. },
  54521. collisionId: collisionIndex,
  54522. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54523. maximumRetry: maximumRetry
  54524. };
  54525. var message = {
  54526. payload: payload,
  54527. taskType: WorkerTaskType.COLLIDE
  54528. };
  54529. this._worker.postMessage(message);
  54530. };
  54531. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54532. this._scene = scene;
  54533. this._scene.registerAfterRender(this._afterRender);
  54534. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54535. this._worker = new Worker(workerUrl);
  54536. this._worker.onmessage = this._onMessageFromWorker;
  54537. var message = {
  54538. payload: {},
  54539. taskType: WorkerTaskType.INIT
  54540. };
  54541. this._worker.postMessage(message);
  54542. };
  54543. CollisionCoordinatorWorker.prototype.destroy = function () {
  54544. this._scene.unregisterAfterRender(this._afterRender);
  54545. this._worker.terminate();
  54546. };
  54547. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54548. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54549. this.onMeshUpdated(mesh);
  54550. };
  54551. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54552. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54553. };
  54554. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54555. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54556. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54557. this.onGeometryUpdated(geometry);
  54558. };
  54559. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54560. this._toRemoveGeometryArray.push(geometry.id);
  54561. };
  54562. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54563. var submeshes = [];
  54564. if (mesh.subMeshes) {
  54565. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54566. var boundingInfo = sm.getBoundingInfo();
  54567. return {
  54568. position: idx,
  54569. verticesStart: sm.verticesStart,
  54570. verticesCount: sm.verticesCount,
  54571. indexStart: sm.indexStart,
  54572. indexCount: sm.indexCount,
  54573. hasMaterial: !!sm.getMaterial(),
  54574. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54575. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54576. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54577. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54578. };
  54579. });
  54580. }
  54581. var geometryId = null;
  54582. if (mesh instanceof BABYLON.Mesh) {
  54583. var geometry = mesh.geometry;
  54584. geometryId = geometry ? geometry.id : null;
  54585. }
  54586. else if (mesh instanceof BABYLON.InstancedMesh) {
  54587. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54588. geometryId = geometry ? geometry.id : null;
  54589. }
  54590. var boundingInfo = mesh.getBoundingInfo();
  54591. return {
  54592. uniqueId: mesh.uniqueId,
  54593. id: mesh.id,
  54594. name: mesh.name,
  54595. geometryId: geometryId,
  54596. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54597. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54598. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54599. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54600. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54601. subMeshes: submeshes,
  54602. checkCollisions: mesh.checkCollisions
  54603. };
  54604. };
  54605. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54606. return {
  54607. id: geometry.id,
  54608. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54609. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54610. indices: new Uint32Array(geometry.getIndices() || []),
  54611. };
  54612. };
  54613. return CollisionCoordinatorWorker;
  54614. }());
  54615. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54616. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54617. function CollisionCoordinatorLegacy() {
  54618. this._scaledPosition = BABYLON.Vector3.Zero();
  54619. this._scaledVelocity = BABYLON.Vector3.Zero();
  54620. this._finalPosition = BABYLON.Vector3.Zero();
  54621. }
  54622. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54623. position.divideToRef(collider._radius, this._scaledPosition);
  54624. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54625. collider.collidedMesh = null;
  54626. collider._retry = 0;
  54627. collider._initialVelocity = this._scaledVelocity;
  54628. collider._initialPosition = this._scaledPosition;
  54629. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54630. this._finalPosition.multiplyInPlace(collider._radius);
  54631. //run the callback
  54632. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54633. };
  54634. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54635. this._scene = scene;
  54636. };
  54637. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54638. //Legacy need no destruction method.
  54639. };
  54640. //No update in legacy mode
  54641. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54642. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54643. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54644. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54645. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54646. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54647. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54648. if (excludedMesh === void 0) { excludedMesh = null; }
  54649. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54650. if (collider._retry >= maximumRetry) {
  54651. finalPosition.copyFrom(position);
  54652. return;
  54653. }
  54654. // Check if this is a mesh else camera or -1
  54655. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54656. collider._initialize(position, velocity, closeDistance);
  54657. // Check all meshes
  54658. for (var index = 0; index < this._scene.meshes.length; index++) {
  54659. var mesh = this._scene.meshes[index];
  54660. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54661. mesh._checkCollision(collider);
  54662. }
  54663. }
  54664. if (!collider.collisionFound) {
  54665. position.addToRef(velocity, finalPosition);
  54666. return;
  54667. }
  54668. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54669. collider._getResponse(position, velocity);
  54670. }
  54671. if (velocity.length() <= closeDistance) {
  54672. finalPosition.copyFrom(position);
  54673. return;
  54674. }
  54675. collider._retry++;
  54676. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54677. };
  54678. return CollisionCoordinatorLegacy;
  54679. }());
  54680. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54681. })(BABYLON || (BABYLON = {}));
  54682. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54683. var BABYLON;
  54684. (function (BABYLON) {
  54685. /**
  54686. * A particle represents one of the element emitted by a particle system.
  54687. * This is mainly define by its coordinates, direction, velocity and age.
  54688. */
  54689. var Particle = /** @class */ (function () {
  54690. /**
  54691. * Creates a new instance Particle
  54692. * @param particleSystem the particle system the particle belongs to
  54693. */
  54694. function Particle(
  54695. /**
  54696. * particleSystem the particle system the particle belongs to.
  54697. */
  54698. particleSystem) {
  54699. this.particleSystem = particleSystem;
  54700. /**
  54701. * The world position of the particle in the scene.
  54702. */
  54703. this.position = BABYLON.Vector3.Zero();
  54704. /**
  54705. * The world direction of the particle in the scene.
  54706. */
  54707. this.direction = BABYLON.Vector3.Zero();
  54708. /**
  54709. * The color of the particle.
  54710. */
  54711. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54712. /**
  54713. * The color change of the particle per step.
  54714. */
  54715. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54716. /**
  54717. * Defines how long will the life of the particle be.
  54718. */
  54719. this.lifeTime = 1.0;
  54720. /**
  54721. * The current age of the particle.
  54722. */
  54723. this.age = 0;
  54724. /**
  54725. * The current size of the particle.
  54726. */
  54727. this.size = 0;
  54728. /**
  54729. * The current scale of the particle.
  54730. */
  54731. this.scale = new BABYLON.Vector2(1, 1);
  54732. /**
  54733. * The current angle of the particle.
  54734. */
  54735. this.angle = 0;
  54736. /**
  54737. * Defines how fast is the angle changing.
  54738. */
  54739. this.angularSpeed = 0;
  54740. /**
  54741. * Defines the cell index used by the particle to be rendered from a sprite.
  54742. */
  54743. this.cellIndex = 0;
  54744. /** @hidden */
  54745. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54746. /** @hidden */
  54747. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54748. /** @hidden */
  54749. this._currentSize1 = 0;
  54750. /** @hidden */
  54751. this._currentSize2 = 0;
  54752. /** @hidden */
  54753. this._currentAngularSpeed1 = 0;
  54754. /** @hidden */
  54755. this._currentAngularSpeed2 = 0;
  54756. /** @hidden */
  54757. this._currentVelocity1 = 0;
  54758. /** @hidden */
  54759. this._currentVelocity2 = 0;
  54760. if (!this.particleSystem.isAnimationSheetEnabled) {
  54761. return;
  54762. }
  54763. this.updateCellInfoFromSystem();
  54764. }
  54765. Particle.prototype.updateCellInfoFromSystem = function () {
  54766. this.cellIndex = this.particleSystem.startSpriteCellID;
  54767. };
  54768. /**
  54769. * Defines how the sprite cell index is updated for the particle
  54770. */
  54771. Particle.prototype.updateCellIndex = function () {
  54772. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54773. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54774. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54775. };
  54776. /**
  54777. * Copy the properties of particle to another one.
  54778. * @param other the particle to copy the information to.
  54779. */
  54780. Particle.prototype.copyTo = function (other) {
  54781. other.position.copyFrom(this.position);
  54782. if (this._initialDirection) {
  54783. if (other._initialDirection) {
  54784. other._initialDirection.copyFrom(this._initialDirection);
  54785. }
  54786. else {
  54787. other._initialDirection = this._initialDirection.clone();
  54788. }
  54789. }
  54790. else {
  54791. other._initialDirection = null;
  54792. }
  54793. other.direction.copyFrom(this.direction);
  54794. other.color.copyFrom(this.color);
  54795. other.colorStep.copyFrom(this.colorStep);
  54796. other.lifeTime = this.lifeTime;
  54797. other.age = this.age;
  54798. other.size = this.size;
  54799. other.scale.copyFrom(this.scale);
  54800. other.angle = this.angle;
  54801. other.angularSpeed = this.angularSpeed;
  54802. other.particleSystem = this.particleSystem;
  54803. other.cellIndex = this.cellIndex;
  54804. if (this._currentColorGradient) {
  54805. other._currentColorGradient = this._currentColorGradient;
  54806. other._currentColor1.copyFrom(this._currentColor1);
  54807. other._currentColor2.copyFrom(this._currentColor2);
  54808. }
  54809. if (this._currentSizeGradient) {
  54810. other._currentSizeGradient = this._currentSizeGradient;
  54811. other._currentSize1 = this._currentSize1;
  54812. other._currentSize2 = this._currentSize2;
  54813. }
  54814. if (this._currentAngularSpeedGradient) {
  54815. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54816. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54817. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54818. }
  54819. if (this._currentVelocityGradient) {
  54820. other._currentVelocityGradient = this._currentVelocityGradient;
  54821. other._currentVelocity1 = this._currentVelocity1;
  54822. other._currentVelocity2 = this._currentVelocity2;
  54823. }
  54824. if (this.particleSystem.isAnimationSheetEnabled) {
  54825. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54826. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54827. }
  54828. };
  54829. return Particle;
  54830. }());
  54831. BABYLON.Particle = Particle;
  54832. })(BABYLON || (BABYLON = {}));
  54833. //# sourceMappingURL=babylon.particle.js.map
  54834. var BABYLON;
  54835. (function (BABYLON) {
  54836. /**
  54837. * This represents a particle system in Babylon.
  54838. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  54839. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54840. * @example https://doc.babylonjs.com/babylon101/particles
  54841. */
  54842. var ParticleSystem = /** @class */ (function () {
  54843. /**
  54844. * Instantiates a particle system.
  54845. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  54846. * @param name The name of the particle system
  54847. * @param capacity The max number of particles alive at the same time
  54848. * @param scene The scene the particle system belongs to
  54849. * @param customEffect a custom effect used to change the way particles are rendered by default
  54850. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54851. * @param epsilon Offset used to render the particles
  54852. */
  54853. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54854. if (customEffect === void 0) { customEffect = null; }
  54855. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54856. if (epsilon === void 0) { epsilon = 0.01; }
  54857. var _this = this;
  54858. /**
  54859. * List of animations used by the particle system.
  54860. */
  54861. this.animations = [];
  54862. /**
  54863. * The rendering group used by the Particle system to chose when to render.
  54864. */
  54865. this.renderingGroupId = 0;
  54866. /**
  54867. * The emitter represents the Mesh or position we are attaching the particle system to.
  54868. */
  54869. this.emitter = null;
  54870. /**
  54871. * The maximum number of particles to emit per frame
  54872. */
  54873. this.emitRate = 10;
  54874. /**
  54875. * If you want to launch only a few particles at once, that can be done, as well.
  54876. */
  54877. this.manualEmitCount = -1;
  54878. /**
  54879. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54880. */
  54881. this.updateSpeed = 0.01;
  54882. /**
  54883. * The amount of time the particle system is running (depends of the overall update speed).
  54884. */
  54885. this.targetStopDuration = 0;
  54886. /**
  54887. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54888. */
  54889. this.disposeOnStop = false;
  54890. /**
  54891. * Minimum power of emitting particles.
  54892. */
  54893. this.minEmitPower = 1;
  54894. /**
  54895. * Maximum power of emitting particles.
  54896. */
  54897. this.maxEmitPower = 1;
  54898. /**
  54899. * Minimum life time of emitting particles.
  54900. */
  54901. this.minLifeTime = 1;
  54902. /**
  54903. * Maximum life time of emitting particles.
  54904. */
  54905. this.maxLifeTime = 1;
  54906. /**
  54907. * Minimum Size of emitting particles.
  54908. */
  54909. this.minSize = 1;
  54910. /**
  54911. * Maximum Size of emitting particles.
  54912. */
  54913. this.maxSize = 1;
  54914. /**
  54915. * Minimum scale of emitting particles on X axis.
  54916. */
  54917. this.minScaleX = 1;
  54918. /**
  54919. * Maximum scale of emitting particles on X axis.
  54920. */
  54921. this.maxScaleX = 1;
  54922. /**
  54923. * Minimum scale of emitting particles on Y axis.
  54924. */
  54925. this.minScaleY = 1;
  54926. /**
  54927. * Maximum scale of emitting particles on Y axis.
  54928. */
  54929. this.maxScaleY = 1;
  54930. /**
  54931. * Gets or sets the minimal initial rotation in radians.
  54932. */
  54933. this.minInitialRotation = 0;
  54934. /**
  54935. * Gets or sets the maximal initial rotation in radians.
  54936. */
  54937. this.maxInitialRotation = 0;
  54938. /**
  54939. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54940. */
  54941. this.minAngularSpeed = 0;
  54942. /**
  54943. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54944. */
  54945. this.maxAngularSpeed = 0;
  54946. /**
  54947. * The layer mask we are rendering the particles through.
  54948. */
  54949. this.layerMask = 0x0FFFFFFF;
  54950. /**
  54951. * This can help using your own shader to render the particle system.
  54952. * The according effect will be created
  54953. */
  54954. this.customShader = null;
  54955. /**
  54956. * By default particle system starts as soon as they are created. This prevents the
  54957. * automatic start to happen and let you decide when to start emitting particles.
  54958. */
  54959. this.preventAutoStart = false;
  54960. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  54961. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  54962. /**
  54963. * Callback triggered when the particle animation is ending.
  54964. */
  54965. this.onAnimationEnd = null;
  54966. /**
  54967. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54968. */
  54969. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54970. /**
  54971. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54972. * to override the particles.
  54973. */
  54974. this.forceDepthWrite = false;
  54975. /**
  54976. * You can use gravity if you want to give an orientation to your particles.
  54977. */
  54978. this.gravity = BABYLON.Vector3.Zero();
  54979. this._colorGradients = null;
  54980. this._sizeGradients = null;
  54981. this._lifeTimeGradients = null;
  54982. this._angularSpeedGradients = null;
  54983. this._velocityGradients = null;
  54984. /**
  54985. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54986. */
  54987. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54988. /**
  54989. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54990. */
  54991. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54992. /**
  54993. * Color the particle will have at the end of its lifetime
  54994. */
  54995. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54996. /**
  54997. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  54998. */
  54999. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55000. /**
  55001. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55002. */
  55003. this.spriteCellChangeSpeed = 1;
  55004. /**
  55005. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55006. */
  55007. this.startSpriteCellID = 0;
  55008. /**
  55009. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55010. */
  55011. this.endSpriteCellID = 0;
  55012. /**
  55013. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55014. */
  55015. this.spriteCellWidth = 0;
  55016. /**
  55017. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55018. */
  55019. this.spriteCellHeight = 0;
  55020. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55021. this.preWarmCycles = 0;
  55022. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55023. this.preWarmStepOffset = 1;
  55024. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55025. this.translationPivot = new BABYLON.Vector2(0, 0);
  55026. /**
  55027. * An event triggered when the system is disposed
  55028. */
  55029. this.onDisposeObservable = new BABYLON.Observable();
  55030. /**
  55031. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55032. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55033. */
  55034. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55035. this._particles = new Array();
  55036. this._stockParticles = new Array();
  55037. this._newPartsExcess = 0;
  55038. this._vertexBuffers = {};
  55039. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55040. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55041. this._scaledDirection = BABYLON.Vector3.Zero();
  55042. this._scaledGravity = BABYLON.Vector3.Zero();
  55043. this._currentRenderId = -1;
  55044. this._useInstancing = false;
  55045. this._started = false;
  55046. this._stopped = false;
  55047. this._actualFrame = 0;
  55048. this._isBillboardBased = true;
  55049. // start of sub system methods
  55050. /**
  55051. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55052. * Its lifetime will start back at 0.
  55053. */
  55054. this.recycleParticle = function (particle) {
  55055. var lastParticle = _this._particles.pop();
  55056. if (lastParticle !== particle) {
  55057. lastParticle.copyTo(particle);
  55058. }
  55059. _this._stockParticles.push(lastParticle);
  55060. };
  55061. this._createParticle = function () {
  55062. var particle;
  55063. if (_this._stockParticles.length !== 0) {
  55064. particle = _this._stockParticles.pop();
  55065. particle.age = 0;
  55066. particle._currentColorGradient = null;
  55067. particle.cellIndex = _this.startSpriteCellID;
  55068. }
  55069. else {
  55070. particle = new BABYLON.Particle(_this);
  55071. }
  55072. return particle;
  55073. };
  55074. this._emitFromParticle = function (particle) {
  55075. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55076. return;
  55077. }
  55078. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55079. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55080. subSystem._rootParticleSystem = _this;
  55081. _this.activeSubSystems.push(subSystem);
  55082. subSystem.start();
  55083. };
  55084. this.id = name;
  55085. this.name = name;
  55086. this._capacity = capacity;
  55087. this._epsilon = epsilon;
  55088. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55089. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55090. this._customEffect = customEffect;
  55091. scene.particleSystems.push(this);
  55092. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55093. this._createIndexBuffer();
  55094. this._createVertexBuffers();
  55095. // Default emitter type
  55096. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55097. this.updateFunction = function (particles) {
  55098. var noiseTextureData = null;
  55099. var noiseTextureSize = null;
  55100. if (_this.noiseTexture) { // We need to get texture data back to CPU
  55101. noiseTextureData = (_this.noiseTexture.readPixels());
  55102. noiseTextureSize = _this.noiseTexture.getSize();
  55103. }
  55104. var _loop_1 = function () {
  55105. particle = particles[index];
  55106. particle.age += _this._scaledUpdateSpeed;
  55107. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55108. _this._emitFromParticle(particle);
  55109. _this.recycleParticle(particle);
  55110. index--;
  55111. return "continue";
  55112. }
  55113. else {
  55114. var ratio = particle.age / particle.lifeTime;
  55115. // Color
  55116. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55117. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55118. if (currentGradient !== particle._currentColorGradient) {
  55119. particle._currentColor1.copyFrom(particle._currentColor2);
  55120. nextGradient.getColorToRef(particle._currentColor2);
  55121. particle._currentColorGradient = currentGradient;
  55122. }
  55123. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55124. });
  55125. }
  55126. else {
  55127. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55128. particle.color.addInPlace(_this._scaledColorStep);
  55129. if (particle.color.a < 0) {
  55130. particle.color.a = 0;
  55131. }
  55132. }
  55133. // Angular speed
  55134. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55135. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55136. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55137. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55138. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55139. particle._currentAngularSpeedGradient = currentGradient;
  55140. }
  55141. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55142. });
  55143. }
  55144. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55145. // Direction
  55146. var directionScale_1 = _this._scaledUpdateSpeed;
  55147. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55148. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55149. if (currentGradient !== particle._currentVelocityGradient) {
  55150. particle._currentVelocity1 = particle._currentVelocity2;
  55151. particle._currentVelocity2 = nextGradient.getFactor();
  55152. particle._currentVelocityGradient = currentGradient;
  55153. }
  55154. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55155. });
  55156. }
  55157. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55158. particle.position.addInPlace(_this._scaledDirection);
  55159. // Noise
  55160. if (noiseTextureData && noiseTextureSize) {
  55161. var localPosition = BABYLON.Tmp.Vector3[0];
  55162. var emitterPosition = BABYLON.Tmp.Vector3[1];
  55163. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  55164. particle.position.subtractToRef(emitterPosition, localPosition);
  55165. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55166. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55167. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55168. var force = BABYLON.Tmp.Vector3[0];
  55169. var scaledForce = BABYLON.Tmp.Vector3[1];
  55170. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  55171. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  55172. particle.direction.addInPlace(scaledForce);
  55173. }
  55174. // Gravity
  55175. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55176. particle.direction.addInPlace(_this._scaledGravity);
  55177. // Size
  55178. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55179. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55180. if (currentGradient !== particle._currentSizeGradient) {
  55181. particle._currentSize1 = particle._currentSize2;
  55182. particle._currentSize2 = nextGradient.getFactor();
  55183. particle._currentSizeGradient = currentGradient;
  55184. }
  55185. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55186. });
  55187. }
  55188. if (_this._isAnimationSheetEnabled) {
  55189. particle.updateCellIndex();
  55190. }
  55191. }
  55192. };
  55193. var particle;
  55194. for (var index = 0; index < particles.length; index++) {
  55195. _loop_1();
  55196. }
  55197. };
  55198. }
  55199. /**
  55200. * Gets the current list of color gradients.
  55201. * You must use addColorGradient and removeColorGradient to udpate this list
  55202. * @returns the list of color gradients
  55203. */
  55204. ParticleSystem.prototype.getColorGradients = function () {
  55205. return this._colorGradients;
  55206. };
  55207. /**
  55208. * Gets the current list of size gradients.
  55209. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55210. * @returns the list of size gradients
  55211. */
  55212. ParticleSystem.prototype.getSizeGradients = function () {
  55213. return this._sizeGradients;
  55214. };
  55215. /**
  55216. * Gets the current list of life time gradients.
  55217. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55218. * @returns the list of life time gradients
  55219. */
  55220. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55221. return this._lifeTimeGradients;
  55222. };
  55223. /**
  55224. * Gets the current list of angular speed gradients.
  55225. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55226. * @returns the list of angular speed gradients
  55227. */
  55228. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55229. return this._angularSpeedGradients;
  55230. };
  55231. /**
  55232. * Gets the current list of velocity gradients.
  55233. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55234. * @returns the list of velocity gradients
  55235. */
  55236. ParticleSystem.prototype.getVelocityGradients = function () {
  55237. return this._velocityGradients;
  55238. };
  55239. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55240. /**
  55241. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55242. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55243. */
  55244. get: function () {
  55245. if (this.particleEmitterType.direction1) {
  55246. return this.particleEmitterType.direction1;
  55247. }
  55248. return BABYLON.Vector3.Zero();
  55249. },
  55250. set: function (value) {
  55251. if (this.particleEmitterType.direction1) {
  55252. this.particleEmitterType.direction1 = value;
  55253. }
  55254. },
  55255. enumerable: true,
  55256. configurable: true
  55257. });
  55258. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55259. /**
  55260. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55261. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55262. */
  55263. get: function () {
  55264. if (this.particleEmitterType.direction2) {
  55265. return this.particleEmitterType.direction2;
  55266. }
  55267. return BABYLON.Vector3.Zero();
  55268. },
  55269. set: function (value) {
  55270. if (this.particleEmitterType.direction2) {
  55271. this.particleEmitterType.direction2 = value;
  55272. }
  55273. },
  55274. enumerable: true,
  55275. configurable: true
  55276. });
  55277. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55278. /**
  55279. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  55280. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55281. */
  55282. get: function () {
  55283. if (this.particleEmitterType.minEmitBox) {
  55284. return this.particleEmitterType.minEmitBox;
  55285. }
  55286. return BABYLON.Vector3.Zero();
  55287. },
  55288. set: function (value) {
  55289. if (this.particleEmitterType.minEmitBox) {
  55290. this.particleEmitterType.minEmitBox = value;
  55291. }
  55292. },
  55293. enumerable: true,
  55294. configurable: true
  55295. });
  55296. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55297. /**
  55298. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  55299. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55300. */
  55301. get: function () {
  55302. if (this.particleEmitterType.maxEmitBox) {
  55303. return this.particleEmitterType.maxEmitBox;
  55304. }
  55305. return BABYLON.Vector3.Zero();
  55306. },
  55307. set: function (value) {
  55308. if (this.particleEmitterType.maxEmitBox) {
  55309. this.particleEmitterType.maxEmitBox = value;
  55310. }
  55311. },
  55312. enumerable: true,
  55313. configurable: true
  55314. });
  55315. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55316. /**
  55317. * Sets a callback that will be triggered when the system is disposed
  55318. */
  55319. set: function (callback) {
  55320. if (this._onDisposeObserver) {
  55321. this.onDisposeObservable.remove(this._onDisposeObserver);
  55322. }
  55323. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55324. },
  55325. enumerable: true,
  55326. configurable: true
  55327. });
  55328. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55329. /**
  55330. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55331. */
  55332. get: function () {
  55333. return this._isAnimationSheetEnabled;
  55334. },
  55335. enumerable: true,
  55336. configurable: true
  55337. });
  55338. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55339. /**
  55340. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55341. */
  55342. get: function () {
  55343. return this._isBillboardBased;
  55344. },
  55345. set: function (value) {
  55346. if (this._isBillboardBased === value) {
  55347. return;
  55348. }
  55349. this._isBillboardBased = value;
  55350. this._resetEffect();
  55351. },
  55352. enumerable: true,
  55353. configurable: true
  55354. });
  55355. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55356. //end of Sub-emitter
  55357. /**
  55358. * Gets the current list of active particles
  55359. */
  55360. get: function () {
  55361. return this._particles;
  55362. },
  55363. enumerable: true,
  55364. configurable: true
  55365. });
  55366. /**
  55367. * Returns the string "ParticleSystem"
  55368. * @returns a string containing the class name
  55369. */
  55370. ParticleSystem.prototype.getClassName = function () {
  55371. return "ParticleSystem";
  55372. };
  55373. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  55374. u = Math.abs(u) * 0.5 + 0.5;
  55375. v = Math.abs(v) * 0.5 + 0.5;
  55376. var wrappedU = ((u * width) % width) | 0;
  55377. var wrappedV = ((v * height) % height) | 0;
  55378. var position = (wrappedU + wrappedV * width) * 4;
  55379. return pixels[position] / 255;
  55380. };
  55381. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55382. var newGradient = new BABYLON.FactorGradient();
  55383. newGradient.gradient = gradient;
  55384. newGradient.factor1 = factor;
  55385. newGradient.factor2 = factor2;
  55386. factorGradients.push(newGradient);
  55387. factorGradients.sort(function (a, b) {
  55388. if (a.gradient < b.gradient) {
  55389. return -1;
  55390. }
  55391. else if (a.gradient > b.gradient) {
  55392. return 1;
  55393. }
  55394. return 0;
  55395. });
  55396. };
  55397. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55398. if (!factorGradients) {
  55399. return;
  55400. }
  55401. var index = 0;
  55402. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55403. var factorGradient = factorGradients_1[_i];
  55404. if (factorGradient.gradient === gradient) {
  55405. factorGradients.splice(index, 1);
  55406. break;
  55407. }
  55408. index++;
  55409. }
  55410. };
  55411. /**
  55412. * Adds a new life time gradient
  55413. * @param gradient defines the gradient to use (between 0 and 1)
  55414. * @param factor defines the life time factor to affect to the specified gradient
  55415. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55416. * @returns the current particle system
  55417. */
  55418. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55419. if (!this._lifeTimeGradients) {
  55420. this._lifeTimeGradients = [];
  55421. }
  55422. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55423. return this;
  55424. };
  55425. /**
  55426. * Remove a specific life time gradient
  55427. * @param gradient defines the gradient to remove
  55428. * @returns the current particle system
  55429. */
  55430. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55431. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55432. return this;
  55433. };
  55434. /**
  55435. * Adds a new size gradient
  55436. * @param gradient defines the gradient to use (between 0 and 1)
  55437. * @param factor defines the size factor to affect to the specified gradient
  55438. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55439. * @returns the current particle system
  55440. */
  55441. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55442. if (!this._sizeGradients) {
  55443. this._sizeGradients = [];
  55444. }
  55445. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55446. return this;
  55447. };
  55448. /**
  55449. * Remove a specific size gradient
  55450. * @param gradient defines the gradient to remove
  55451. * @returns the current particle system
  55452. */
  55453. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55454. this._removeFactorGradient(this._sizeGradients, gradient);
  55455. return this;
  55456. };
  55457. /**
  55458. * Adds a new angular speed gradient
  55459. * @param gradient defines the gradient to use (between 0 and 1)
  55460. * @param factor defines the size factor to affect to the specified gradient
  55461. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55462. * @returns the current particle system
  55463. */
  55464. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55465. if (!this._angularSpeedGradients) {
  55466. this._angularSpeedGradients = [];
  55467. }
  55468. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55469. return this;
  55470. };
  55471. /**
  55472. * Remove a specific angular speed gradient
  55473. * @param gradient defines the gradient to remove
  55474. * @returns the current particle system
  55475. */
  55476. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55477. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55478. return this;
  55479. };
  55480. /**
  55481. * Adds a new velocity gradient
  55482. * @param gradient defines the gradient to use (between 0 and 1)
  55483. * @param factor defines the size factor to affect to the specified gradient
  55484. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55485. * @returns the current particle system
  55486. */
  55487. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55488. if (!this._velocityGradients) {
  55489. this._velocityGradients = [];
  55490. }
  55491. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55492. return this;
  55493. };
  55494. /**
  55495. * Remove a specific velocity gradient
  55496. * @param gradient defines the gradient to remove
  55497. * @returns the current particle system
  55498. */
  55499. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55500. this._removeFactorGradient(this._velocityGradients, gradient);
  55501. return this;
  55502. };
  55503. /**
  55504. * Adds a new color gradient
  55505. * @param gradient defines the gradient to use (between 0 and 1)
  55506. * @param color defines the color to affect to the specified gradient
  55507. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55508. */
  55509. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55510. if (!this._colorGradients) {
  55511. this._colorGradients = [];
  55512. }
  55513. var colorGradient = new BABYLON.ColorGradient();
  55514. colorGradient.gradient = gradient;
  55515. colorGradient.color1 = color;
  55516. colorGradient.color2 = color2;
  55517. this._colorGradients.push(colorGradient);
  55518. this._colorGradients.sort(function (a, b) {
  55519. if (a.gradient < b.gradient) {
  55520. return -1;
  55521. }
  55522. else if (a.gradient > b.gradient) {
  55523. return 1;
  55524. }
  55525. return 0;
  55526. });
  55527. return this;
  55528. };
  55529. /**
  55530. * Remove a specific color gradient
  55531. * @param gradient defines the gradient to remove
  55532. */
  55533. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55534. if (!this._colorGradients) {
  55535. return this;
  55536. }
  55537. var index = 0;
  55538. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55539. var colorGradient = _a[_i];
  55540. if (colorGradient.gradient === gradient) {
  55541. this._colorGradients.splice(index, 1);
  55542. break;
  55543. }
  55544. index++;
  55545. }
  55546. return this;
  55547. };
  55548. ParticleSystem.prototype._resetEffect = function () {
  55549. if (this._vertexBuffer) {
  55550. this._vertexBuffer.dispose();
  55551. this._vertexBuffer = null;
  55552. }
  55553. if (this._spriteBuffer) {
  55554. this._spriteBuffer.dispose();
  55555. this._spriteBuffer = null;
  55556. }
  55557. this._createVertexBuffers();
  55558. };
  55559. ParticleSystem.prototype._createVertexBuffers = function () {
  55560. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55561. if (this._isAnimationSheetEnabled) {
  55562. this._vertexBufferSize += 1;
  55563. }
  55564. if (!this._isBillboardBased) {
  55565. this._vertexBufferSize += 3;
  55566. }
  55567. var engine = this._scene.getEngine();
  55568. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55569. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55570. var dataOffset = 0;
  55571. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55572. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55573. dataOffset += 3;
  55574. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55575. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55576. dataOffset += 4;
  55577. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55578. this._vertexBuffers["angle"] = options;
  55579. dataOffset += 1;
  55580. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55581. this._vertexBuffers["size"] = size;
  55582. dataOffset += 2;
  55583. if (this._isAnimationSheetEnabled) {
  55584. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55585. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55586. dataOffset += 1;
  55587. }
  55588. if (!this._isBillboardBased) {
  55589. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55590. this._vertexBuffers["direction"] = directionBuffer;
  55591. dataOffset += 3;
  55592. }
  55593. var offsets;
  55594. if (this._useInstancing) {
  55595. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55596. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55597. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55598. }
  55599. else {
  55600. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55601. dataOffset += 2;
  55602. }
  55603. this._vertexBuffers["offset"] = offsets;
  55604. };
  55605. ParticleSystem.prototype._createIndexBuffer = function () {
  55606. if (this._useInstancing) {
  55607. return;
  55608. }
  55609. var indices = [];
  55610. var index = 0;
  55611. for (var count = 0; count < this._capacity; count++) {
  55612. indices.push(index);
  55613. indices.push(index + 1);
  55614. indices.push(index + 2);
  55615. indices.push(index);
  55616. indices.push(index + 2);
  55617. indices.push(index + 3);
  55618. index += 4;
  55619. }
  55620. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55621. };
  55622. /**
  55623. * Gets the maximum number of particles active at the same time.
  55624. * @returns The max number of active particles.
  55625. */
  55626. ParticleSystem.prototype.getCapacity = function () {
  55627. return this._capacity;
  55628. };
  55629. /**
  55630. * Gets Wether there are still active particles in the system.
  55631. * @returns True if it is alive, otherwise false.
  55632. */
  55633. ParticleSystem.prototype.isAlive = function () {
  55634. return this._alive;
  55635. };
  55636. /**
  55637. * Gets Wether the system has been started.
  55638. * @returns True if it has been started, otherwise false.
  55639. */
  55640. ParticleSystem.prototype.isStarted = function () {
  55641. return this._started;
  55642. };
  55643. /**
  55644. * Starts the particle system and begins to emit
  55645. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  55646. */
  55647. ParticleSystem.prototype.start = function (delay) {
  55648. var _this = this;
  55649. if (delay === void 0) { delay = 0; }
  55650. if (delay) {
  55651. setTimeout(function () {
  55652. _this.start(0);
  55653. }, delay);
  55654. return;
  55655. }
  55656. this._started = true;
  55657. this._stopped = false;
  55658. this._actualFrame = 0;
  55659. if (this.subEmitters && this.subEmitters.length != 0) {
  55660. this.activeSubSystems = new Array();
  55661. }
  55662. if (this.preWarmCycles) {
  55663. for (var index = 0; index < this.preWarmCycles; index++) {
  55664. this.animate(true);
  55665. }
  55666. }
  55667. };
  55668. /**
  55669. * Stops the particle system.
  55670. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  55671. */
  55672. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55673. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55674. this._stopped = true;
  55675. if (stopSubEmitters) {
  55676. this._stopSubEmitters();
  55677. }
  55678. };
  55679. // animation sheet
  55680. /**
  55681. * Remove all active particles
  55682. */
  55683. ParticleSystem.prototype.reset = function () {
  55684. this._stockParticles = [];
  55685. this._particles = [];
  55686. };
  55687. /**
  55688. * @hidden (for internal use only)
  55689. */
  55690. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55691. var offset = index * this._vertexBufferSize;
  55692. this._vertexData[offset++] = particle.position.x;
  55693. this._vertexData[offset++] = particle.position.y;
  55694. this._vertexData[offset++] = particle.position.z;
  55695. this._vertexData[offset++] = particle.color.r;
  55696. this._vertexData[offset++] = particle.color.g;
  55697. this._vertexData[offset++] = particle.color.b;
  55698. this._vertexData[offset++] = particle.color.a;
  55699. this._vertexData[offset++] = particle.angle;
  55700. this._vertexData[offset++] = particle.scale.x * particle.size;
  55701. this._vertexData[offset++] = particle.scale.y * particle.size;
  55702. if (this._isAnimationSheetEnabled) {
  55703. this._vertexData[offset++] = particle.cellIndex;
  55704. }
  55705. if (!this._isBillboardBased) {
  55706. if (particle._initialDirection) {
  55707. this._vertexData[offset++] = particle._initialDirection.x;
  55708. this._vertexData[offset++] = particle._initialDirection.y;
  55709. this._vertexData[offset++] = particle._initialDirection.z;
  55710. }
  55711. else {
  55712. this._vertexData[offset++] = particle.direction.x;
  55713. this._vertexData[offset++] = particle.direction.y;
  55714. this._vertexData[offset++] = particle.direction.z;
  55715. }
  55716. }
  55717. if (!this._useInstancing) {
  55718. if (this._isAnimationSheetEnabled) {
  55719. if (offsetX === 0)
  55720. offsetX = this._epsilon;
  55721. else if (offsetX === 1)
  55722. offsetX = 1 - this._epsilon;
  55723. if (offsetY === 0)
  55724. offsetY = this._epsilon;
  55725. else if (offsetY === 1)
  55726. offsetY = 1 - this._epsilon;
  55727. }
  55728. this._vertexData[offset++] = offsetX;
  55729. this._vertexData[offset++] = offsetY;
  55730. }
  55731. };
  55732. ParticleSystem.prototype._stopSubEmitters = function () {
  55733. if (!this.activeSubSystems) {
  55734. return;
  55735. }
  55736. this.activeSubSystems.forEach(function (subSystem) {
  55737. subSystem.stop(true);
  55738. });
  55739. this.activeSubSystems = new Array();
  55740. };
  55741. ParticleSystem.prototype._removeFromRoot = function () {
  55742. if (!this._rootParticleSystem) {
  55743. return;
  55744. }
  55745. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55746. if (index !== -1) {
  55747. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55748. }
  55749. };
  55750. // End of sub system methods
  55751. ParticleSystem.prototype._update = function (newParticles) {
  55752. // Update current
  55753. this._alive = this._particles.length > 0;
  55754. if (this.emitter.position) {
  55755. var emitterMesh = this.emitter;
  55756. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  55757. }
  55758. else {
  55759. var emitterPosition = this.emitter;
  55760. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55761. }
  55762. this.updateFunction(this._particles);
  55763. // Add new ones
  55764. var particle;
  55765. var _loop_2 = function () {
  55766. if (this_1._particles.length === this_1._capacity) {
  55767. return "break";
  55768. }
  55769. particle = this_1._createParticle();
  55770. this_1._particles.push(particle);
  55771. // Emitter
  55772. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55773. if (this_1.startPositionFunction) {
  55774. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  55775. }
  55776. else {
  55777. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  55778. }
  55779. if (this_1.startDirectionFunction) {
  55780. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  55781. }
  55782. else {
  55783. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  55784. }
  55785. if (emitPower === 0) {
  55786. if (!particle._initialDirection) {
  55787. particle._initialDirection = particle.direction.clone();
  55788. }
  55789. else {
  55790. particle._initialDirection.copyFrom(particle.direction);
  55791. }
  55792. }
  55793. else {
  55794. particle._initialDirection = null;
  55795. }
  55796. particle.direction.scaleInPlace(emitPower);
  55797. // Life time
  55798. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55799. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55800. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55801. var factorGradient1 = currentGradient;
  55802. var factorGradient2 = nextGradient;
  55803. var lifeTime1 = factorGradient1.getFactor();
  55804. var lifeTime2 = factorGradient2.getFactor();
  55805. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55806. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55807. });
  55808. }
  55809. else {
  55810. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55811. }
  55812. // Size
  55813. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55814. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55815. }
  55816. else {
  55817. particle._currentSizeGradient = this_1._sizeGradients[0];
  55818. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55819. particle.size = particle._currentSize1;
  55820. if (this_1._sizeGradients.length > 1) {
  55821. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55822. }
  55823. else {
  55824. particle._currentSize2 = particle._currentSize1;
  55825. }
  55826. }
  55827. // Size and scale
  55828. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55829. // Angle
  55830. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55831. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55832. }
  55833. else {
  55834. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55835. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55836. particle._currentAngularSpeed1 = particle.angularSpeed;
  55837. if (this_1._angularSpeedGradients.length > 1) {
  55838. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55839. }
  55840. else {
  55841. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55842. }
  55843. }
  55844. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55845. // Velocity
  55846. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55847. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55848. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55849. if (this_1._velocityGradients.length > 1) {
  55850. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55851. }
  55852. else {
  55853. particle._currentVelocity2 = particle._currentVelocity1;
  55854. }
  55855. }
  55856. // Color
  55857. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55858. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55859. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55860. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55861. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55862. }
  55863. else {
  55864. particle._currentColorGradient = this_1._colorGradients[0];
  55865. particle._currentColorGradient.getColorToRef(particle.color);
  55866. particle._currentColor1.copyFrom(particle.color);
  55867. if (this_1._colorGradients.length > 1) {
  55868. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55869. }
  55870. else {
  55871. particle._currentColor2.copyFrom(particle.color);
  55872. }
  55873. }
  55874. // Sheet
  55875. if (this_1._isAnimationSheetEnabled) {
  55876. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55877. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55878. }
  55879. };
  55880. var this_1 = this, step;
  55881. for (var index = 0; index < newParticles; index++) {
  55882. var state_1 = _loop_2();
  55883. if (state_1 === "break")
  55884. break;
  55885. }
  55886. };
  55887. /** @hidden */
  55888. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55889. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55890. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55891. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55892. if (isAnimationSheetEnabled) {
  55893. attributeNamesOrOptions.push("cellIndex");
  55894. }
  55895. if (!isBillboardBased) {
  55896. attributeNamesOrOptions.push("direction");
  55897. }
  55898. return attributeNamesOrOptions;
  55899. };
  55900. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55901. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55902. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55903. if (isAnimationSheetEnabled) {
  55904. effectCreationOption.push("particlesInfos");
  55905. }
  55906. return effectCreationOption;
  55907. };
  55908. ParticleSystem.prototype._getEffect = function () {
  55909. if (this._customEffect) {
  55910. return this._customEffect;
  55911. }
  55912. ;
  55913. var defines = [];
  55914. if (this._scene.clipPlane) {
  55915. defines.push("#define CLIPPLANE");
  55916. }
  55917. if (this._isAnimationSheetEnabled) {
  55918. defines.push("#define ANIMATESHEET");
  55919. }
  55920. if (this._isBillboardBased) {
  55921. defines.push("#define BILLBOARD");
  55922. switch (this.billboardMode) {
  55923. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55924. defines.push("#define BILLBOARDY");
  55925. break;
  55926. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55927. default:
  55928. break;
  55929. }
  55930. }
  55931. // Effect
  55932. var join = defines.join("\n");
  55933. if (this._cachedDefines !== join) {
  55934. this._cachedDefines = join;
  55935. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55936. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55937. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55938. }
  55939. return this._effect;
  55940. };
  55941. /**
  55942. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55943. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55944. */
  55945. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55946. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55947. if (!this._started)
  55948. return;
  55949. if (!preWarmOnly) {
  55950. var effect = this._getEffect();
  55951. // Check
  55952. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55953. return;
  55954. if (this._currentRenderId === this._scene.getRenderId()) {
  55955. return;
  55956. }
  55957. this._currentRenderId = this._scene.getRenderId();
  55958. }
  55959. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55960. // determine the number of particles we need to create
  55961. var newParticles;
  55962. if (this.manualEmitCount > -1) {
  55963. newParticles = this.manualEmitCount;
  55964. this._newPartsExcess = 0;
  55965. this.manualEmitCount = 0;
  55966. }
  55967. else {
  55968. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55969. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55970. }
  55971. if (this._newPartsExcess > 1.0) {
  55972. newParticles += this._newPartsExcess >> 0;
  55973. this._newPartsExcess -= this._newPartsExcess >> 0;
  55974. }
  55975. this._alive = false;
  55976. if (!this._stopped) {
  55977. this._actualFrame += this._scaledUpdateSpeed;
  55978. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55979. this.stop();
  55980. }
  55981. else {
  55982. newParticles = 0;
  55983. }
  55984. this._update(newParticles);
  55985. // Stopped?
  55986. if (this._stopped) {
  55987. if (!this._alive) {
  55988. this._started = false;
  55989. if (this.onAnimationEnd) {
  55990. this.onAnimationEnd();
  55991. }
  55992. if (this.disposeOnStop) {
  55993. this._scene._toBeDisposed.push(this);
  55994. }
  55995. }
  55996. }
  55997. if (!preWarmOnly) {
  55998. // Update VBO
  55999. var offset = 0;
  56000. for (var index = 0; index < this._particles.length; index++) {
  56001. var particle = this._particles[index];
  56002. this._appendParticleVertices(offset, particle);
  56003. offset += this._useInstancing ? 1 : 4;
  56004. }
  56005. if (this._vertexBuffer) {
  56006. this._vertexBuffer.update(this._vertexData);
  56007. }
  56008. }
  56009. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56010. this.stop();
  56011. }
  56012. };
  56013. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56014. this._appendParticleVertex(offset++, particle, 0, 0);
  56015. if (!this._useInstancing) {
  56016. this._appendParticleVertex(offset++, particle, 1, 0);
  56017. this._appendParticleVertex(offset++, particle, 1, 1);
  56018. this._appendParticleVertex(offset++, particle, 0, 1);
  56019. }
  56020. };
  56021. /**
  56022. * Rebuilds the particle system.
  56023. */
  56024. ParticleSystem.prototype.rebuild = function () {
  56025. this._createIndexBuffer();
  56026. if (this._vertexBuffer) {
  56027. this._vertexBuffer._rebuild();
  56028. }
  56029. };
  56030. /**
  56031. * Is this system ready to be used/rendered
  56032. * @return true if the system is ready
  56033. */
  56034. ParticleSystem.prototype.isReady = function () {
  56035. var effect = this._getEffect();
  56036. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56037. return false;
  56038. }
  56039. return true;
  56040. };
  56041. /**
  56042. * Renders the particle system in its current state.
  56043. * @returns the current number of particles
  56044. */
  56045. ParticleSystem.prototype.render = function () {
  56046. var effect = this._getEffect();
  56047. // Check
  56048. if (!this.isReady() || !this._particles.length) {
  56049. return 0;
  56050. }
  56051. var engine = this._scene.getEngine();
  56052. // Render
  56053. engine.enableEffect(effect);
  56054. engine.setState(false);
  56055. var viewMatrix = this._scene.getViewMatrix();
  56056. effect.setTexture("diffuseSampler", this.particleTexture);
  56057. effect.setMatrix("view", viewMatrix);
  56058. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56059. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56060. var baseSize = this.particleTexture.getBaseSize();
  56061. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56062. }
  56063. effect.setVector2("translationPivot", this.translationPivot);
  56064. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56065. if (this._isBillboardBased) {
  56066. var camera = this._scene.activeCamera;
  56067. effect.setVector3("eyePosition", camera.globalPosition);
  56068. }
  56069. if (this._scene.clipPlane) {
  56070. var clipPlane = this._scene.clipPlane;
  56071. var invView = viewMatrix.clone();
  56072. invView.invert();
  56073. effect.setMatrix("invView", invView);
  56074. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56075. }
  56076. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56077. // Draw order
  56078. switch (this.blendMode) {
  56079. case ParticleSystem.BLENDMODE_ADD:
  56080. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56081. break;
  56082. case ParticleSystem.BLENDMODE_ONEONE:
  56083. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56084. break;
  56085. case ParticleSystem.BLENDMODE_STANDARD:
  56086. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56087. break;
  56088. }
  56089. if (this.forceDepthWrite) {
  56090. engine.setDepthWrite(true);
  56091. }
  56092. if (this._useInstancing) {
  56093. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56094. engine.unbindInstanceAttributes();
  56095. }
  56096. else {
  56097. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56098. }
  56099. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56100. return this._particles.length;
  56101. };
  56102. /**
  56103. * Disposes the particle system and free the associated resources
  56104. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56105. */
  56106. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56107. if (disposeTexture === void 0) { disposeTexture = true; }
  56108. if (this._vertexBuffer) {
  56109. this._vertexBuffer.dispose();
  56110. this._vertexBuffer = null;
  56111. }
  56112. if (this._spriteBuffer) {
  56113. this._spriteBuffer.dispose();
  56114. this._spriteBuffer = null;
  56115. }
  56116. if (this._indexBuffer) {
  56117. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56118. this._indexBuffer = null;
  56119. }
  56120. if (disposeTexture && this.particleTexture) {
  56121. this.particleTexture.dispose();
  56122. this.particleTexture = null;
  56123. }
  56124. if (disposeTexture && this.noiseTexture) {
  56125. this.noiseTexture.dispose();
  56126. this.noiseTexture = null;
  56127. }
  56128. this._removeFromRoot();
  56129. // Remove from scene
  56130. var index = this._scene.particleSystems.indexOf(this);
  56131. if (index > -1) {
  56132. this._scene.particleSystems.splice(index, 1);
  56133. }
  56134. // Callback
  56135. this.onDisposeObservable.notifyObservers(this);
  56136. this.onDisposeObservable.clear();
  56137. };
  56138. /**
  56139. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56140. * @param radius The radius of the sphere to emit from
  56141. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56142. * @returns the emitter
  56143. */
  56144. ParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56145. if (radius === void 0) { radius = 1; }
  56146. if (radiusRange === void 0) { radiusRange = 1; }
  56147. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56148. this.particleEmitterType = particleEmitter;
  56149. return particleEmitter;
  56150. };
  56151. /**
  56152. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56153. * @param radius The radius of the sphere to emit from
  56154. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56155. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56156. * @returns the emitter
  56157. */
  56158. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56159. if (radius === void 0) { radius = 1; }
  56160. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56161. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56162. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56163. this.particleEmitterType = particleEmitter;
  56164. return particleEmitter;
  56165. };
  56166. /**
  56167. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56168. * @param radius The radius of the cone to emit from
  56169. * @param angle The base angle of the cone
  56170. * @returns the emitter
  56171. */
  56172. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56173. if (radius === void 0) { radius = 1; }
  56174. if (angle === void 0) { angle = Math.PI / 4; }
  56175. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56176. this.particleEmitterType = particleEmitter;
  56177. return particleEmitter;
  56178. };
  56179. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56180. /**
  56181. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56182. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56183. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56184. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56185. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56186. * @returns the emitter
  56187. */
  56188. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56189. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56190. this.particleEmitterType = particleEmitter;
  56191. this.direction1 = direction1;
  56192. this.direction2 = direction2;
  56193. this.minEmitBox = minEmitBox;
  56194. this.maxEmitBox = maxEmitBox;
  56195. return particleEmitter;
  56196. };
  56197. // Clone
  56198. /**
  56199. * Clones the particle system.
  56200. * @param name The name of the cloned object
  56201. * @param newEmitter The new emitter to use
  56202. * @returns the cloned particle system
  56203. */
  56204. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56205. var custom = null;
  56206. var program = null;
  56207. if (this.customShader != null) {
  56208. program = this.customShader;
  56209. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56210. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56211. }
  56212. else if (this._customEffect) {
  56213. custom = this._customEffect;
  56214. }
  56215. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56216. result.customShader = program;
  56217. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56218. if (newEmitter === undefined) {
  56219. newEmitter = this.emitter;
  56220. }
  56221. result.emitter = newEmitter;
  56222. if (this.particleTexture) {
  56223. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56224. }
  56225. if (!this.preventAutoStart) {
  56226. result.start();
  56227. }
  56228. return result;
  56229. };
  56230. /**
  56231. * Serializes the particle system to a JSON object.
  56232. * @returns the JSON object
  56233. */
  56234. ParticleSystem.prototype.serialize = function () {
  56235. var serializationObject = {};
  56236. ParticleSystem._Serialize(serializationObject, this);
  56237. serializationObject.textureMask = this.textureMask.asArray();
  56238. serializationObject.customShader = this.customShader;
  56239. serializationObject.preventAutoStart = this.preventAutoStart;
  56240. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56241. return serializationObject;
  56242. };
  56243. /** @hidden */
  56244. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56245. serializationObject.name = particleSystem.name;
  56246. serializationObject.id = particleSystem.id;
  56247. serializationObject.capacity = particleSystem.getCapacity();
  56248. // Emitter
  56249. if (particleSystem.emitter.position) {
  56250. var emitterMesh = particleSystem.emitter;
  56251. serializationObject.emitterId = emitterMesh.id;
  56252. }
  56253. else {
  56254. var emitterPosition = particleSystem.emitter;
  56255. serializationObject.emitter = emitterPosition.asArray();
  56256. }
  56257. // Emitter
  56258. if (particleSystem.particleEmitterType) {
  56259. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56260. }
  56261. if (particleSystem.particleTexture) {
  56262. serializationObject.textureName = particleSystem.particleTexture.name;
  56263. }
  56264. // Animations
  56265. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56266. // Particle system
  56267. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56268. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56269. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56270. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56271. serializationObject.minSize = particleSystem.minSize;
  56272. serializationObject.maxSize = particleSystem.maxSize;
  56273. serializationObject.minScaleX = particleSystem.minScaleX;
  56274. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56275. serializationObject.minScaleY = particleSystem.minScaleY;
  56276. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56277. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56278. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56279. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56280. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56281. serializationObject.emitRate = particleSystem.emitRate;
  56282. serializationObject.gravity = particleSystem.gravity.asArray();
  56283. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  56284. serializationObject.color1 = particleSystem.color1.asArray();
  56285. serializationObject.color2 = particleSystem.color2.asArray();
  56286. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56287. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56288. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56289. serializationObject.blendMode = particleSystem.blendMode;
  56290. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56291. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56292. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56293. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56294. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56295. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56296. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56297. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56298. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56299. var colorGradients = particleSystem.getColorGradients();
  56300. if (colorGradients) {
  56301. serializationObject.colorGradients = [];
  56302. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56303. var colorGradient = colorGradients_1[_i];
  56304. var serializedGradient = {
  56305. gradient: colorGradient.gradient,
  56306. color1: colorGradient.color1.asArray()
  56307. };
  56308. if (colorGradient.color2) {
  56309. serializedGradient.color2 = colorGradient.color2.asArray();
  56310. }
  56311. serializationObject.colorGradients.push(serializedGradient);
  56312. }
  56313. }
  56314. var sizeGradients = particleSystem.getSizeGradients();
  56315. if (sizeGradients) {
  56316. serializationObject.sizeGradients = [];
  56317. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56318. var sizeGradient = sizeGradients_1[_a];
  56319. var serializedGradient = {
  56320. gradient: sizeGradient.gradient,
  56321. factor1: sizeGradient.factor1
  56322. };
  56323. if (sizeGradient.factor2 !== undefined) {
  56324. serializedGradient.factor2 = sizeGradient.factor2;
  56325. }
  56326. serializationObject.sizeGradients.push(serializedGradient);
  56327. }
  56328. }
  56329. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56330. if (angularSpeedGradients) {
  56331. serializationObject.angularSpeedGradients = [];
  56332. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56333. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56334. var serializedGradient = {
  56335. gradient: angularSpeedGradient.gradient,
  56336. factor1: angularSpeedGradient.factor1
  56337. };
  56338. if (angularSpeedGradient.factor2 !== undefined) {
  56339. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56340. }
  56341. serializationObject.angularSpeedGradients.push(serializedGradient);
  56342. }
  56343. }
  56344. var velocityGradients = particleSystem.getVelocityGradients();
  56345. if (velocityGradients) {
  56346. serializationObject.velocityGradients = [];
  56347. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56348. var velocityGradient = velocityGradients_1[_c];
  56349. var serializedGradient = {
  56350. gradient: velocityGradient.gradient,
  56351. factor1: velocityGradient.factor1
  56352. };
  56353. if (velocityGradient.factor2 !== undefined) {
  56354. serializedGradient.factor2 = velocityGradient.factor2;
  56355. }
  56356. serializationObject.velocityGradients.push(serializedGradient);
  56357. }
  56358. }
  56359. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  56360. var noiseTexture = particleSystem.noiseTexture;
  56361. serializationObject.noiseTexture = noiseTexture.serialize();
  56362. }
  56363. };
  56364. /** @hidden */
  56365. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56366. // Texture
  56367. if (parsedParticleSystem.textureName) {
  56368. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56369. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56370. }
  56371. // Emitter
  56372. if (parsedParticleSystem.emitterId === undefined) {
  56373. particleSystem.emitter = BABYLON.Vector3.Zero();
  56374. }
  56375. else if (parsedParticleSystem.emitterId) {
  56376. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56377. }
  56378. else {
  56379. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56380. }
  56381. // Misc.
  56382. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56383. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56384. }
  56385. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56386. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56387. }
  56388. // Animations
  56389. if (parsedParticleSystem.animations) {
  56390. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56391. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56392. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56393. }
  56394. }
  56395. if (parsedParticleSystem.autoAnimate) {
  56396. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56397. }
  56398. // Particle system
  56399. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56400. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56401. particleSystem.minSize = parsedParticleSystem.minSize;
  56402. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56403. if (parsedParticleSystem.minScaleX) {
  56404. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56405. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56406. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56407. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56408. }
  56409. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56410. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56411. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56412. }
  56413. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56414. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56415. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56416. }
  56417. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56418. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56419. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56420. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56421. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56422. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56423. if (parsedParticleSystem.noiseStrength) {
  56424. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  56425. }
  56426. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56427. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56428. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56429. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56430. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56431. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56432. if (parsedParticleSystem.colorGradients) {
  56433. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56434. var colorGradient = _a[_i];
  56435. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56436. }
  56437. }
  56438. if (parsedParticleSystem.sizeGradients) {
  56439. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56440. var sizeGradient = _c[_b];
  56441. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56442. }
  56443. }
  56444. if (parsedParticleSystem.angularSpeedGradients) {
  56445. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56446. var angularSpeedGradient = _e[_d];
  56447. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56448. }
  56449. }
  56450. if (parsedParticleSystem.velocityGradients) {
  56451. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56452. var velocityGradient = _g[_f];
  56453. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56454. }
  56455. }
  56456. if (parsedParticleSystem.noiseTexture) {
  56457. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  56458. }
  56459. // Emitter
  56460. var emitterType;
  56461. if (parsedParticleSystem.particleEmitterType) {
  56462. switch (parsedParticleSystem.particleEmitterType.type) {
  56463. case "SphereParticleEmitter":
  56464. emitterType = new BABYLON.SphereParticleEmitter();
  56465. break;
  56466. case "SphereDirectedParticleEmitter":
  56467. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56468. break;
  56469. case "ConeEmitter":
  56470. case "ConeParticleEmitter":
  56471. emitterType = new BABYLON.ConeParticleEmitter();
  56472. break;
  56473. case "BoxEmitter":
  56474. case "BoxParticleEmitter":
  56475. default:
  56476. emitterType = new BABYLON.BoxParticleEmitter();
  56477. break;
  56478. }
  56479. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56480. }
  56481. else {
  56482. emitterType = new BABYLON.BoxParticleEmitter();
  56483. emitterType.parse(parsedParticleSystem);
  56484. }
  56485. particleSystem.particleEmitterType = emitterType;
  56486. // Animation sheet
  56487. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56488. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56489. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56490. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56491. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56492. };
  56493. /**
  56494. * Parses a JSON object to create a particle system.
  56495. * @param parsedParticleSystem The JSON object to parse
  56496. * @param scene The scene to create the particle system in
  56497. * @param rootUrl The root url to use to load external dependencies like texture
  56498. * @returns the Parsed particle system
  56499. */
  56500. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56501. var name = parsedParticleSystem.name;
  56502. var custom = null;
  56503. var program = null;
  56504. if (parsedParticleSystem.customShader) {
  56505. program = parsedParticleSystem.customShader;
  56506. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56507. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56508. }
  56509. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56510. particleSystem.customShader = program;
  56511. if (parsedParticleSystem.id) {
  56512. particleSystem.id = parsedParticleSystem.id;
  56513. }
  56514. // Auto start
  56515. if (parsedParticleSystem.preventAutoStart) {
  56516. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56517. }
  56518. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56519. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56520. if (!particleSystem.preventAutoStart) {
  56521. particleSystem.start();
  56522. }
  56523. return particleSystem;
  56524. };
  56525. /**
  56526. * Source color is added to the destination color without alpha affecting the result.
  56527. */
  56528. ParticleSystem.BLENDMODE_ONEONE = 0;
  56529. /**
  56530. * Blend current color and particle color using particle’s alpha.
  56531. */
  56532. ParticleSystem.BLENDMODE_STANDARD = 1;
  56533. /**
  56534. * Add current color and particle color multiplied by particle’s alpha.
  56535. */
  56536. ParticleSystem.BLENDMODE_ADD = 2;
  56537. return ParticleSystem;
  56538. }());
  56539. BABYLON.ParticleSystem = ParticleSystem;
  56540. })(BABYLON || (BABYLON = {}));
  56541. //# sourceMappingURL=babylon.particleSystem.js.map
  56542. var BABYLON;
  56543. (function (BABYLON) {
  56544. /**
  56545. * Particle emitter emitting particles from the inside of a box.
  56546. * It emits the particles randomly between 2 given directions.
  56547. */
  56548. var BoxParticleEmitter = /** @class */ (function () {
  56549. /**
  56550. * Creates a new instance BoxParticleEmitter
  56551. */
  56552. function BoxParticleEmitter() {
  56553. /**
  56554. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56555. */
  56556. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56557. /**
  56558. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56559. */
  56560. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56561. /**
  56562. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56563. */
  56564. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56565. /**
  56566. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  56567. */
  56568. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56569. }
  56570. /**
  56571. * Called by the particle System when the direction is computed for the created particle.
  56572. * @param worldMatrix is the world matrix of the particle system
  56573. * @param directionToUpdate is the direction vector to update with the result
  56574. * @param particle is the particle we are computed the direction for
  56575. */
  56576. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56577. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56578. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56579. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56580. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56581. };
  56582. /**
  56583. * Called by the particle System when the position is computed for the created particle.
  56584. * @param worldMatrix is the world matrix of the particle system
  56585. * @param positionToUpdate is the position vector to update with the result
  56586. * @param particle is the particle we are computed the position for
  56587. */
  56588. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56589. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56590. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56591. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56592. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56593. };
  56594. /**
  56595. * Clones the current emitter and returns a copy of it
  56596. * @returns the new emitter
  56597. */
  56598. BoxParticleEmitter.prototype.clone = function () {
  56599. var newOne = new BoxParticleEmitter();
  56600. BABYLON.Tools.DeepCopy(this, newOne);
  56601. return newOne;
  56602. };
  56603. /**
  56604. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56605. * @param effect defines the update shader
  56606. */
  56607. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56608. effect.setVector3("direction1", this.direction1);
  56609. effect.setVector3("direction2", this.direction2);
  56610. effect.setVector3("minEmitBox", this.minEmitBox);
  56611. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56612. };
  56613. /**
  56614. * Returns a string to use to update the GPU particles update shader
  56615. * @returns a string containng the defines string
  56616. */
  56617. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56618. return "#define BOXEMITTER";
  56619. };
  56620. /**
  56621. * Returns the string "BoxParticleEmitter"
  56622. * @returns a string containing the class name
  56623. */
  56624. BoxParticleEmitter.prototype.getClassName = function () {
  56625. return "BoxParticleEmitter";
  56626. };
  56627. /**
  56628. * Serializes the particle system to a JSON object.
  56629. * @returns the JSON object
  56630. */
  56631. BoxParticleEmitter.prototype.serialize = function () {
  56632. var serializationObject = {};
  56633. serializationObject.type = this.getClassName();
  56634. serializationObject.direction1 = this.direction1.asArray();
  56635. serializationObject.direction2 = this.direction2.asArray();
  56636. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56637. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56638. return serializationObject;
  56639. };
  56640. /**
  56641. * Parse properties from a JSON object
  56642. * @param serializationObject defines the JSON object
  56643. */
  56644. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56645. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56646. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56647. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56648. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56649. };
  56650. return BoxParticleEmitter;
  56651. }());
  56652. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56653. })(BABYLON || (BABYLON = {}));
  56654. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56655. var BABYLON;
  56656. (function (BABYLON) {
  56657. /**
  56658. * Particle emitter emitting particles from the inside of a cone.
  56659. * It emits the particles alongside the cone volume from the base to the particle.
  56660. * The emission direction might be randomized.
  56661. */
  56662. var ConeParticleEmitter = /** @class */ (function () {
  56663. /**
  56664. * Creates a new instance ConeParticleEmitter
  56665. * @param radius the radius of the emission cone (1 by default)
  56666. * @param angles the cone base angle (PI by default)
  56667. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56668. */
  56669. function ConeParticleEmitter(radius, angle,
  56670. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56671. directionRandomizer) {
  56672. if (radius === void 0) { radius = 1; }
  56673. if (angle === void 0) { angle = Math.PI; }
  56674. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56675. this.directionRandomizer = directionRandomizer;
  56676. /**
  56677. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56678. */
  56679. this.radiusRange = 1;
  56680. /**
  56681. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56682. */
  56683. this.heightRange = 1;
  56684. this.angle = angle;
  56685. this.radius = radius;
  56686. }
  56687. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56688. /**
  56689. * Gets or sets the radius of the emission cone
  56690. */
  56691. get: function () {
  56692. return this._radius;
  56693. },
  56694. set: function (value) {
  56695. this._radius = value;
  56696. this._buildHeight();
  56697. },
  56698. enumerable: true,
  56699. configurable: true
  56700. });
  56701. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56702. /**
  56703. * Gets or sets the angle of the emission cone
  56704. */
  56705. get: function () {
  56706. return this._angle;
  56707. },
  56708. set: function (value) {
  56709. this._angle = value;
  56710. this._buildHeight();
  56711. },
  56712. enumerable: true,
  56713. configurable: true
  56714. });
  56715. ConeParticleEmitter.prototype._buildHeight = function () {
  56716. if (this._angle !== 0) {
  56717. this._height = this._radius / Math.tan(this._angle / 2);
  56718. }
  56719. else {
  56720. this._height = 1;
  56721. }
  56722. };
  56723. /**
  56724. * Called by the particle System when the direction is computed for the created particle.
  56725. * @param worldMatrix is the world matrix of the particle system
  56726. * @param directionToUpdate is the direction vector to update with the result
  56727. * @param particle is the particle we are computed the direction for
  56728. */
  56729. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56730. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56731. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56732. }
  56733. else {
  56734. // measure the direction Vector from the emitter to the particle.
  56735. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56736. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56737. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56738. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56739. direction.x += randX;
  56740. direction.y += randY;
  56741. direction.z += randZ;
  56742. direction.normalize();
  56743. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56744. }
  56745. };
  56746. /**
  56747. * Called by the particle System when the position is computed for the created particle.
  56748. * @param worldMatrix is the world matrix of the particle system
  56749. * @param positionToUpdate is the position vector to update with the result
  56750. * @param particle is the particle we are computed the position for
  56751. */
  56752. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56753. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56754. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56755. // Better distribution in a cone at normal angles.
  56756. h = 1 - h * h;
  56757. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56758. radius = radius * h;
  56759. var randX = radius * Math.sin(s);
  56760. var randZ = radius * Math.cos(s);
  56761. var randY = h * this._height;
  56762. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56763. };
  56764. /**
  56765. * Clones the current emitter and returns a copy of it
  56766. * @returns the new emitter
  56767. */
  56768. ConeParticleEmitter.prototype.clone = function () {
  56769. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56770. BABYLON.Tools.DeepCopy(this, newOne);
  56771. return newOne;
  56772. };
  56773. /**
  56774. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56775. * @param effect defines the update shader
  56776. */
  56777. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56778. effect.setFloat2("radius", this._radius, this.radiusRange);
  56779. effect.setFloat("coneAngle", this._angle);
  56780. effect.setFloat2("height", this._height, this.heightRange);
  56781. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56782. };
  56783. /**
  56784. * Returns a string to use to update the GPU particles update shader
  56785. * @returns a string containng the defines string
  56786. */
  56787. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56788. return "#define CONEEMITTER";
  56789. };
  56790. /**
  56791. * Returns the string "ConeParticleEmitter"
  56792. * @returns a string containing the class name
  56793. */
  56794. ConeParticleEmitter.prototype.getClassName = function () {
  56795. return "ConeParticleEmitter";
  56796. };
  56797. /**
  56798. * Serializes the particle system to a JSON object.
  56799. * @returns the JSON object
  56800. */
  56801. ConeParticleEmitter.prototype.serialize = function () {
  56802. var serializationObject = {};
  56803. serializationObject.type = this.getClassName();
  56804. serializationObject.radius = this._radius;
  56805. serializationObject.angle = this._angle;
  56806. serializationObject.directionRandomizer = this.directionRandomizer;
  56807. return serializationObject;
  56808. };
  56809. /**
  56810. * Parse properties from a JSON object
  56811. * @param serializationObject defines the JSON object
  56812. */
  56813. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56814. this.radius = serializationObject.radius;
  56815. this.angle = serializationObject.angle;
  56816. this.directionRandomizer = serializationObject.directionRandomizer;
  56817. };
  56818. return ConeParticleEmitter;
  56819. }());
  56820. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56821. })(BABYLON || (BABYLON = {}));
  56822. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56823. var BABYLON;
  56824. (function (BABYLON) {
  56825. /**
  56826. * Particle emitter emitting particles from the inside of a sphere.
  56827. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56828. */
  56829. var SphereParticleEmitter = /** @class */ (function () {
  56830. /**
  56831. * Creates a new instance SphereParticleEmitter
  56832. * @param radius the radius of the emission sphere (1 by default)
  56833. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56834. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56835. */
  56836. function SphereParticleEmitter(
  56837. /**
  56838. * The radius of the emission sphere.
  56839. */
  56840. radius,
  56841. /**
  56842. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  56843. */
  56844. radiusRange,
  56845. /**
  56846. * How much to randomize the particle direction [0-1].
  56847. */
  56848. directionRandomizer) {
  56849. if (radius === void 0) { radius = 1; }
  56850. if (radiusRange === void 0) { radiusRange = 1; }
  56851. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56852. this.radius = radius;
  56853. this.radiusRange = radiusRange;
  56854. this.directionRandomizer = directionRandomizer;
  56855. }
  56856. /**
  56857. * Called by the particle System when the direction is computed for the created particle.
  56858. * @param worldMatrix is the world matrix of the particle system
  56859. * @param directionToUpdate is the direction vector to update with the result
  56860. * @param particle is the particle we are computed the direction for
  56861. */
  56862. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56863. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56864. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56865. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56866. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56867. direction.x += randX;
  56868. direction.y += randY;
  56869. direction.z += randZ;
  56870. direction.normalize();
  56871. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56872. };
  56873. /**
  56874. * Called by the particle System when the position is computed for the created particle.
  56875. * @param worldMatrix is the world matrix of the particle system
  56876. * @param positionToUpdate is the position vector to update with the result
  56877. * @param particle is the particle we are computed the position for
  56878. */
  56879. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56880. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56881. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56882. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56883. var theta = Math.acos(2 * v - 1);
  56884. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56885. var randY = randRadius * Math.cos(theta);
  56886. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56887. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56888. };
  56889. /**
  56890. * Clones the current emitter and returns a copy of it
  56891. * @returns the new emitter
  56892. */
  56893. SphereParticleEmitter.prototype.clone = function () {
  56894. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56895. BABYLON.Tools.DeepCopy(this, newOne);
  56896. return newOne;
  56897. };
  56898. /**
  56899. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56900. * @param effect defines the update shader
  56901. */
  56902. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56903. effect.setFloat("radius", this.radius);
  56904. effect.setFloat("radiusRange", this.radiusRange);
  56905. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56906. };
  56907. /**
  56908. * Returns a string to use to update the GPU particles update shader
  56909. * @returns a string containng the defines string
  56910. */
  56911. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56912. return "#define SPHEREEMITTER";
  56913. };
  56914. /**
  56915. * Returns the string "SphereParticleEmitter"
  56916. * @returns a string containing the class name
  56917. */
  56918. SphereParticleEmitter.prototype.getClassName = function () {
  56919. return "SphereParticleEmitter";
  56920. };
  56921. /**
  56922. * Serializes the particle system to a JSON object.
  56923. * @returns the JSON object
  56924. */
  56925. SphereParticleEmitter.prototype.serialize = function () {
  56926. var serializationObject = {};
  56927. serializationObject.type = this.getClassName();
  56928. serializationObject.radius = this.radius;
  56929. serializationObject.radiusRange = this.radiusRange;
  56930. serializationObject.directionRandomizer = this.directionRandomizer;
  56931. return serializationObject;
  56932. };
  56933. /**
  56934. * Parse properties from a JSON object
  56935. * @param serializationObject defines the JSON object
  56936. */
  56937. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56938. this.radius = serializationObject.radius;
  56939. this.radiusRange = serializationObject.radiusRange;
  56940. this.directionRandomizer = serializationObject.directionRandomizer;
  56941. };
  56942. return SphereParticleEmitter;
  56943. }());
  56944. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56945. /**
  56946. * Particle emitter emitting particles from the inside of a sphere.
  56947. * It emits the particles randomly between two vectors.
  56948. */
  56949. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56950. __extends(SphereDirectedParticleEmitter, _super);
  56951. /**
  56952. * Creates a new instance SphereDirectedParticleEmitter
  56953. * @param radius the radius of the emission sphere (1 by default)
  56954. * @param direction1 the min limit of the emission direction (up vector by default)
  56955. * @param direction2 the max limit of the emission direction (up vector by default)
  56956. */
  56957. function SphereDirectedParticleEmitter(radius,
  56958. /**
  56959. * The min limit of the emission direction.
  56960. */
  56961. direction1,
  56962. /**
  56963. * The max limit of the emission direction.
  56964. */
  56965. direction2) {
  56966. if (radius === void 0) { radius = 1; }
  56967. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56968. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56969. var _this = _super.call(this, radius) || this;
  56970. _this.direction1 = direction1;
  56971. _this.direction2 = direction2;
  56972. return _this;
  56973. }
  56974. /**
  56975. * Called by the particle System when the direction is computed for the created particle.
  56976. * @param worldMatrix is the world matrix of the particle system
  56977. * @param directionToUpdate is the direction vector to update with the result
  56978. * @param particle is the particle we are computed the direction for
  56979. */
  56980. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56981. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56982. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56983. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56984. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56985. };
  56986. /**
  56987. * Clones the current emitter and returns a copy of it
  56988. * @returns the new emitter
  56989. */
  56990. SphereDirectedParticleEmitter.prototype.clone = function () {
  56991. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56992. BABYLON.Tools.DeepCopy(this, newOne);
  56993. return newOne;
  56994. };
  56995. /**
  56996. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56997. * @param effect defines the update shader
  56998. */
  56999. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57000. effect.setFloat("radius", this.radius);
  57001. effect.setFloat("radiusRange", this.radiusRange);
  57002. effect.setVector3("direction1", this.direction1);
  57003. effect.setVector3("direction2", this.direction2);
  57004. };
  57005. /**
  57006. * Returns a string to use to update the GPU particles update shader
  57007. * @returns a string containng the defines string
  57008. */
  57009. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57010. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57011. };
  57012. /**
  57013. * Returns the string "SphereDirectedParticleEmitter"
  57014. * @returns a string containing the class name
  57015. */
  57016. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57017. return "SphereDirectedParticleEmitter";
  57018. };
  57019. /**
  57020. * Serializes the particle system to a JSON object.
  57021. * @returns the JSON object
  57022. */
  57023. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57024. var serializationObject = _super.prototype.serialize.call(this);
  57025. serializationObject.direction1 = this.direction1.asArray();
  57026. serializationObject.direction2 = this.direction2.asArray();
  57027. return serializationObject;
  57028. };
  57029. /**
  57030. * Parse properties from a JSON object
  57031. * @param serializationObject defines the JSON object
  57032. */
  57033. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57034. _super.prototype.parse.call(this, serializationObject);
  57035. this.direction1.copyFrom(serializationObject.direction1);
  57036. this.direction2.copyFrom(serializationObject.direction2);
  57037. };
  57038. return SphereDirectedParticleEmitter;
  57039. }(SphereParticleEmitter));
  57040. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57041. })(BABYLON || (BABYLON = {}));
  57042. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57043. var BABYLON;
  57044. (function (BABYLON) {
  57045. // Adds the parsers to the scene parsers.
  57046. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57047. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57048. if (!individualParser) {
  57049. return;
  57050. }
  57051. // Particles Systems
  57052. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57053. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57054. var parsedParticleSystem = parsedData.particleSystems[index];
  57055. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57056. }
  57057. }
  57058. });
  57059. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57060. if (parsedParticleSystem.activeParticleCount) {
  57061. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57062. return ps;
  57063. }
  57064. else {
  57065. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57066. return ps;
  57067. }
  57068. });
  57069. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57070. if (uniformsNames === void 0) { uniformsNames = []; }
  57071. if (samplers === void 0) { samplers = []; }
  57072. if (defines === void 0) { defines = ""; }
  57073. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57074. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57075. if (defines.indexOf(" BILLBOARD") === -1) {
  57076. defines += "\n#define BILLBOARD\n";
  57077. }
  57078. if (samplers.indexOf("diffuseSampler") === -1) {
  57079. samplers.push("diffuseSampler");
  57080. }
  57081. return this.createEffect({
  57082. vertex: "particles",
  57083. fragmentElement: fragmentName
  57084. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57085. };
  57086. })(BABYLON || (BABYLON = {}));
  57087. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57088. var BABYLON;
  57089. (function (BABYLON) {
  57090. var ShaderMaterial = /** @class */ (function (_super) {
  57091. __extends(ShaderMaterial, _super);
  57092. function ShaderMaterial(name, scene, shaderPath, options) {
  57093. var _this = _super.call(this, name, scene) || this;
  57094. _this._textures = {};
  57095. _this._textureArrays = {};
  57096. _this._floats = {};
  57097. _this._ints = {};
  57098. _this._floatsArrays = {};
  57099. _this._colors3 = {};
  57100. _this._colors3Arrays = {};
  57101. _this._colors4 = {};
  57102. _this._vectors2 = {};
  57103. _this._vectors3 = {};
  57104. _this._vectors4 = {};
  57105. _this._matrices = {};
  57106. _this._matrices3x3 = {};
  57107. _this._matrices2x2 = {};
  57108. _this._vectors2Arrays = {};
  57109. _this._vectors3Arrays = {};
  57110. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57111. _this._shaderPath = shaderPath;
  57112. options.needAlphaBlending = options.needAlphaBlending || false;
  57113. options.needAlphaTesting = options.needAlphaTesting || false;
  57114. options.attributes = options.attributes || ["position", "normal", "uv"];
  57115. options.uniforms = options.uniforms || ["worldViewProjection"];
  57116. options.uniformBuffers = options.uniformBuffers || [];
  57117. options.samplers = options.samplers || [];
  57118. options.defines = options.defines || [];
  57119. _this._options = options;
  57120. return _this;
  57121. }
  57122. ShaderMaterial.prototype.getClassName = function () {
  57123. return "ShaderMaterial";
  57124. };
  57125. ShaderMaterial.prototype.needAlphaBlending = function () {
  57126. return this._options.needAlphaBlending;
  57127. };
  57128. ShaderMaterial.prototype.needAlphaTesting = function () {
  57129. return this._options.needAlphaTesting;
  57130. };
  57131. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57132. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57133. this._options.uniforms.push(uniformName);
  57134. }
  57135. };
  57136. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57137. if (this._options.samplers.indexOf(name) === -1) {
  57138. this._options.samplers.push(name);
  57139. }
  57140. this._textures[name] = texture;
  57141. return this;
  57142. };
  57143. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57144. if (this._options.samplers.indexOf(name) === -1) {
  57145. this._options.samplers.push(name);
  57146. }
  57147. this._checkUniform(name);
  57148. this._textureArrays[name] = textures;
  57149. return this;
  57150. };
  57151. ShaderMaterial.prototype.setFloat = function (name, value) {
  57152. this._checkUniform(name);
  57153. this._floats[name] = value;
  57154. return this;
  57155. };
  57156. ShaderMaterial.prototype.setInt = function (name, value) {
  57157. this._checkUniform(name);
  57158. this._ints[name] = value;
  57159. return this;
  57160. };
  57161. ShaderMaterial.prototype.setFloats = function (name, value) {
  57162. this._checkUniform(name);
  57163. this._floatsArrays[name] = value;
  57164. return this;
  57165. };
  57166. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57167. this._checkUniform(name);
  57168. this._colors3[name] = value;
  57169. return this;
  57170. };
  57171. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57172. this._checkUniform(name);
  57173. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57174. color.toArray(arr, arr.length);
  57175. return arr;
  57176. }, []);
  57177. return this;
  57178. };
  57179. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57180. this._checkUniform(name);
  57181. this._colors4[name] = value;
  57182. return this;
  57183. };
  57184. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57185. this._checkUniform(name);
  57186. this._vectors2[name] = value;
  57187. return this;
  57188. };
  57189. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57190. this._checkUniform(name);
  57191. this._vectors3[name] = value;
  57192. return this;
  57193. };
  57194. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57195. this._checkUniform(name);
  57196. this._vectors4[name] = value;
  57197. return this;
  57198. };
  57199. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57200. this._checkUniform(name);
  57201. this._matrices[name] = value;
  57202. return this;
  57203. };
  57204. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57205. this._checkUniform(name);
  57206. this._matrices3x3[name] = value;
  57207. return this;
  57208. };
  57209. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57210. this._checkUniform(name);
  57211. this._matrices2x2[name] = value;
  57212. return this;
  57213. };
  57214. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57215. this._checkUniform(name);
  57216. this._vectors2Arrays[name] = value;
  57217. return this;
  57218. };
  57219. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57220. this._checkUniform(name);
  57221. this._vectors3Arrays[name] = value;
  57222. return this;
  57223. };
  57224. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57225. if (!mesh) {
  57226. return true;
  57227. }
  57228. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57229. return false;
  57230. }
  57231. return false;
  57232. };
  57233. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57234. var scene = this.getScene();
  57235. var engine = scene.getEngine();
  57236. if (!this.checkReadyOnEveryCall) {
  57237. if (this._renderId === scene.getRenderId()) {
  57238. if (this._checkCache(scene, mesh, useInstances)) {
  57239. return true;
  57240. }
  57241. }
  57242. }
  57243. // Instances
  57244. var defines = [];
  57245. var attribs = [];
  57246. var fallbacks = new BABYLON.EffectFallbacks();
  57247. if (useInstances) {
  57248. defines.push("#define INSTANCES");
  57249. }
  57250. for (var index = 0; index < this._options.defines.length; index++) {
  57251. defines.push(this._options.defines[index]);
  57252. }
  57253. for (var index = 0; index < this._options.attributes.length; index++) {
  57254. attribs.push(this._options.attributes[index]);
  57255. }
  57256. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57257. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57258. defines.push("#define VERTEXCOLOR");
  57259. }
  57260. // Bones
  57261. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57262. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57263. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57264. if (mesh.numBoneInfluencers > 4) {
  57265. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57266. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57267. }
  57268. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57269. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57270. fallbacks.addCPUSkinningFallback(0, mesh);
  57271. if (this._options.uniforms.indexOf("mBones") === -1) {
  57272. this._options.uniforms.push("mBones");
  57273. }
  57274. }
  57275. else {
  57276. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57277. }
  57278. // Textures
  57279. for (var name in this._textures) {
  57280. if (!this._textures[name].isReady()) {
  57281. return false;
  57282. }
  57283. }
  57284. // Alpha test
  57285. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57286. defines.push("#define ALPHATEST");
  57287. }
  57288. var previousEffect = this._effect;
  57289. var join = defines.join("\n");
  57290. this._effect = engine.createEffect(this._shaderPath, {
  57291. attributes: attribs,
  57292. uniformsNames: this._options.uniforms,
  57293. uniformBuffersNames: this._options.uniformBuffers,
  57294. samplers: this._options.samplers,
  57295. defines: join,
  57296. fallbacks: fallbacks,
  57297. onCompiled: this.onCompiled,
  57298. onError: this.onError
  57299. }, engine);
  57300. if (!this._effect.isReady()) {
  57301. return false;
  57302. }
  57303. if (previousEffect !== this._effect) {
  57304. scene.resetCachedMaterial();
  57305. }
  57306. this._renderId = scene.getRenderId();
  57307. return true;
  57308. };
  57309. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57310. var scene = this.getScene();
  57311. if (!this._effect) {
  57312. return;
  57313. }
  57314. if (this._options.uniforms.indexOf("world") !== -1) {
  57315. this._effect.setMatrix("world", world);
  57316. }
  57317. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57318. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57319. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57320. }
  57321. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57322. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57323. }
  57324. };
  57325. ShaderMaterial.prototype.bind = function (world, mesh) {
  57326. // Std values
  57327. this.bindOnlyWorldMatrix(world);
  57328. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57329. if (this._options.uniforms.indexOf("view") !== -1) {
  57330. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57331. }
  57332. if (this._options.uniforms.indexOf("projection") !== -1) {
  57333. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57334. }
  57335. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57336. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57337. }
  57338. // Bones
  57339. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57340. var name;
  57341. // Texture
  57342. for (name in this._textures) {
  57343. this._effect.setTexture(name, this._textures[name]);
  57344. }
  57345. // Texture arrays
  57346. for (name in this._textureArrays) {
  57347. this._effect.setTextureArray(name, this._textureArrays[name]);
  57348. }
  57349. // Int
  57350. for (name in this._ints) {
  57351. this._effect.setInt(name, this._ints[name]);
  57352. }
  57353. // Float
  57354. for (name in this._floats) {
  57355. this._effect.setFloat(name, this._floats[name]);
  57356. }
  57357. // Floats
  57358. for (name in this._floatsArrays) {
  57359. this._effect.setArray(name, this._floatsArrays[name]);
  57360. }
  57361. // Color3
  57362. for (name in this._colors3) {
  57363. this._effect.setColor3(name, this._colors3[name]);
  57364. }
  57365. for (name in this._colors3Arrays) {
  57366. this._effect.setArray3(name, this._colors3Arrays[name]);
  57367. }
  57368. // Color4
  57369. for (name in this._colors4) {
  57370. var color = this._colors4[name];
  57371. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57372. }
  57373. // Vector2
  57374. for (name in this._vectors2) {
  57375. this._effect.setVector2(name, this._vectors2[name]);
  57376. }
  57377. // Vector3
  57378. for (name in this._vectors3) {
  57379. this._effect.setVector3(name, this._vectors3[name]);
  57380. }
  57381. // Vector4
  57382. for (name in this._vectors4) {
  57383. this._effect.setVector4(name, this._vectors4[name]);
  57384. }
  57385. // Matrix
  57386. for (name in this._matrices) {
  57387. this._effect.setMatrix(name, this._matrices[name]);
  57388. }
  57389. // Matrix 3x3
  57390. for (name in this._matrices3x3) {
  57391. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57392. }
  57393. // Matrix 2x2
  57394. for (name in this._matrices2x2) {
  57395. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57396. }
  57397. // Vector2Array
  57398. for (name in this._vectors2Arrays) {
  57399. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57400. }
  57401. // Vector3Array
  57402. for (name in this._vectors3Arrays) {
  57403. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57404. }
  57405. }
  57406. this._afterBind(mesh);
  57407. };
  57408. ShaderMaterial.prototype.getActiveTextures = function () {
  57409. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57410. for (var name in this._textures) {
  57411. activeTextures.push(this._textures[name]);
  57412. }
  57413. for (var name in this._textureArrays) {
  57414. var array = this._textureArrays[name];
  57415. for (var index = 0; index < array.length; index++) {
  57416. activeTextures.push(array[index]);
  57417. }
  57418. }
  57419. return activeTextures;
  57420. };
  57421. ShaderMaterial.prototype.hasTexture = function (texture) {
  57422. if (_super.prototype.hasTexture.call(this, texture)) {
  57423. return true;
  57424. }
  57425. for (var name in this._textures) {
  57426. if (this._textures[name] === texture) {
  57427. return true;
  57428. }
  57429. }
  57430. for (var name in this._textureArrays) {
  57431. var array = this._textureArrays[name];
  57432. for (var index = 0; index < array.length; index++) {
  57433. if (array[index] === texture) {
  57434. return true;
  57435. }
  57436. }
  57437. }
  57438. return false;
  57439. };
  57440. ShaderMaterial.prototype.clone = function (name) {
  57441. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57442. return newShaderMaterial;
  57443. };
  57444. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57445. if (forceDisposeTextures) {
  57446. var name;
  57447. for (name in this._textures) {
  57448. this._textures[name].dispose();
  57449. }
  57450. for (name in this._textureArrays) {
  57451. var array = this._textureArrays[name];
  57452. for (var index = 0; index < array.length; index++) {
  57453. array[index].dispose();
  57454. }
  57455. }
  57456. }
  57457. this._textures = {};
  57458. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57459. };
  57460. ShaderMaterial.prototype.serialize = function () {
  57461. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57462. serializationObject.customType = "BABYLON.ShaderMaterial";
  57463. serializationObject.options = this._options;
  57464. serializationObject.shaderPath = this._shaderPath;
  57465. var name;
  57466. // Texture
  57467. serializationObject.textures = {};
  57468. for (name in this._textures) {
  57469. serializationObject.textures[name] = this._textures[name].serialize();
  57470. }
  57471. // Texture arrays
  57472. serializationObject.textureArrays = {};
  57473. for (name in this._textureArrays) {
  57474. serializationObject.textureArrays[name] = [];
  57475. var array = this._textureArrays[name];
  57476. for (var index = 0; index < array.length; index++) {
  57477. serializationObject.textureArrays[name].push(array[index].serialize());
  57478. }
  57479. }
  57480. // Float
  57481. serializationObject.floats = {};
  57482. for (name in this._floats) {
  57483. serializationObject.floats[name] = this._floats[name];
  57484. }
  57485. // Float s
  57486. serializationObject.FloatArrays = {};
  57487. for (name in this._floatsArrays) {
  57488. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57489. }
  57490. // Color3
  57491. serializationObject.colors3 = {};
  57492. for (name in this._colors3) {
  57493. serializationObject.colors3[name] = this._colors3[name].asArray();
  57494. }
  57495. // Color3 array
  57496. serializationObject.colors3Arrays = {};
  57497. for (name in this._colors3Arrays) {
  57498. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57499. }
  57500. // Color4
  57501. serializationObject.colors4 = {};
  57502. for (name in this._colors4) {
  57503. serializationObject.colors4[name] = this._colors4[name].asArray();
  57504. }
  57505. // Vector2
  57506. serializationObject.vectors2 = {};
  57507. for (name in this._vectors2) {
  57508. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57509. }
  57510. // Vector3
  57511. serializationObject.vectors3 = {};
  57512. for (name in this._vectors3) {
  57513. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57514. }
  57515. // Vector4
  57516. serializationObject.vectors4 = {};
  57517. for (name in this._vectors4) {
  57518. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57519. }
  57520. // Matrix
  57521. serializationObject.matrices = {};
  57522. for (name in this._matrices) {
  57523. serializationObject.matrices[name] = this._matrices[name].asArray();
  57524. }
  57525. // Matrix 3x3
  57526. serializationObject.matrices3x3 = {};
  57527. for (name in this._matrices3x3) {
  57528. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57529. }
  57530. // Matrix 2x2
  57531. serializationObject.matrices2x2 = {};
  57532. for (name in this._matrices2x2) {
  57533. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57534. }
  57535. // Vector2Array
  57536. serializationObject.vectors2Arrays = {};
  57537. for (name in this._vectors2Arrays) {
  57538. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57539. }
  57540. // Vector3Array
  57541. serializationObject.vectors3Arrays = {};
  57542. for (name in this._vectors3Arrays) {
  57543. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57544. }
  57545. return serializationObject;
  57546. };
  57547. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57548. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57549. var name;
  57550. // Texture
  57551. for (name in source.textures) {
  57552. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57553. }
  57554. // Texture arrays
  57555. for (name in source.textureArrays) {
  57556. var array = source.textureArrays[name];
  57557. var textureArray = new Array();
  57558. for (var index = 0; index < array.length; index++) {
  57559. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57560. }
  57561. material.setTextureArray(name, textureArray);
  57562. }
  57563. // Float
  57564. for (name in source.floats) {
  57565. material.setFloat(name, source.floats[name]);
  57566. }
  57567. // Float s
  57568. for (name in source.floatsArrays) {
  57569. material.setFloats(name, source.floatsArrays[name]);
  57570. }
  57571. // Color3
  57572. for (name in source.colors3) {
  57573. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57574. }
  57575. // Color3 arrays
  57576. for (name in source.colors3Arrays) {
  57577. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57578. if (i % 3 === 0) {
  57579. arr.push([num]);
  57580. }
  57581. else {
  57582. arr[arr.length - 1].push(num);
  57583. }
  57584. return arr;
  57585. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57586. material.setColor3Array(name, colors);
  57587. }
  57588. // Color4
  57589. for (name in source.colors4) {
  57590. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57591. }
  57592. // Vector2
  57593. for (name in source.vectors2) {
  57594. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  57595. }
  57596. // Vector3
  57597. for (name in source.vectors3) {
  57598. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  57599. }
  57600. // Vector4
  57601. for (name in source.vectors4) {
  57602. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  57603. }
  57604. // Matrix
  57605. for (name in source.matrices) {
  57606. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  57607. }
  57608. // Matrix 3x3
  57609. for (name in source.matrices3x3) {
  57610. material.setMatrix3x3(name, source.matrices3x3[name]);
  57611. }
  57612. // Matrix 2x2
  57613. for (name in source.matrices2x2) {
  57614. material.setMatrix2x2(name, source.matrices2x2[name]);
  57615. }
  57616. // Vector2Array
  57617. for (name in source.vectors2Arrays) {
  57618. material.setArray2(name, source.vectors2Arrays[name]);
  57619. }
  57620. // Vector3Array
  57621. for (name in source.vectors3Arrays) {
  57622. material.setArray3(name, source.vectors3Arrays[name]);
  57623. }
  57624. return material;
  57625. };
  57626. return ShaderMaterial;
  57627. }(BABYLON.Material));
  57628. BABYLON.ShaderMaterial = ShaderMaterial;
  57629. })(BABYLON || (BABYLON = {}));
  57630. //# sourceMappingURL=babylon.shaderMaterial.js.map
  57631. var BABYLON;
  57632. (function (BABYLON) {
  57633. var GroundMesh = /** @class */ (function (_super) {
  57634. __extends(GroundMesh, _super);
  57635. function GroundMesh(name, scene) {
  57636. var _this = _super.call(this, name, scene) || this;
  57637. _this.generateOctree = false;
  57638. return _this;
  57639. }
  57640. GroundMesh.prototype.getClassName = function () {
  57641. return "GroundMesh";
  57642. };
  57643. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  57644. get: function () {
  57645. return Math.min(this._subdivisionsX, this._subdivisionsY);
  57646. },
  57647. enumerable: true,
  57648. configurable: true
  57649. });
  57650. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  57651. get: function () {
  57652. return this._subdivisionsX;
  57653. },
  57654. enumerable: true,
  57655. configurable: true
  57656. });
  57657. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  57658. get: function () {
  57659. return this._subdivisionsY;
  57660. },
  57661. enumerable: true,
  57662. configurable: true
  57663. });
  57664. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  57665. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  57666. this._subdivisionsX = chunksCount;
  57667. this._subdivisionsY = chunksCount;
  57668. this.subdivide(chunksCount);
  57669. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  57670. };
  57671. /**
  57672. * Returns a height (y) value in the Worl system :
  57673. * the ground altitude at the coordinates (x, z) expressed in the World system.
  57674. * Returns the ground y position if (x, z) are outside the ground surface.
  57675. */
  57676. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  57677. var world = this.getWorldMatrix();
  57678. var invMat = BABYLON.Tmp.Matrix[5];
  57679. world.invertToRef(invMat);
  57680. var tmpVect = BABYLON.Tmp.Vector3[8];
  57681. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  57682. x = tmpVect.x;
  57683. z = tmpVect.z;
  57684. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57685. return this.position.y;
  57686. }
  57687. if (!this._heightQuads || this._heightQuads.length == 0) {
  57688. this._initHeightQuads();
  57689. this._computeHeightQuads();
  57690. }
  57691. var facet = this._getFacetAt(x, z);
  57692. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  57693. // return y in the World system
  57694. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  57695. return tmpVect.y;
  57696. };
  57697. /**
  57698. * Returns a normalized vector (Vector3) orthogonal to the ground
  57699. * at the ground coordinates (x, z) expressed in the World system.
  57700. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  57701. */
  57702. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  57703. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  57704. this.getNormalAtCoordinatesToRef(x, z, normal);
  57705. return normal;
  57706. };
  57707. /**
  57708. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  57709. * at the ground coordinates (x, z) expressed in the World system.
  57710. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  57711. * Returns the GroundMesh.
  57712. */
  57713. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  57714. var world = this.getWorldMatrix();
  57715. var tmpMat = BABYLON.Tmp.Matrix[5];
  57716. world.invertToRef(tmpMat);
  57717. var tmpVect = BABYLON.Tmp.Vector3[8];
  57718. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  57719. x = tmpVect.x;
  57720. z = tmpVect.z;
  57721. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57722. return this;
  57723. }
  57724. if (!this._heightQuads || this._heightQuads.length == 0) {
  57725. this._initHeightQuads();
  57726. this._computeHeightQuads();
  57727. }
  57728. var facet = this._getFacetAt(x, z);
  57729. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  57730. return this;
  57731. };
  57732. /**
  57733. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  57734. * if the ground has been updated.
  57735. * This can be used in the render loop.
  57736. * Returns the GroundMesh.
  57737. */
  57738. GroundMesh.prototype.updateCoordinateHeights = function () {
  57739. if (!this._heightQuads || this._heightQuads.length == 0) {
  57740. this._initHeightQuads();
  57741. }
  57742. this._computeHeightQuads();
  57743. return this;
  57744. };
  57745. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  57746. GroundMesh.prototype._getFacetAt = function (x, z) {
  57747. // retrieve col and row from x, z coordinates in the ground local system
  57748. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  57749. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  57750. var quad = this._heightQuads[row * this._subdivisionsX + col];
  57751. var facet;
  57752. if (z < quad.slope.x * x + quad.slope.y) {
  57753. facet = quad.facet1;
  57754. }
  57755. else {
  57756. facet = quad.facet2;
  57757. }
  57758. return facet;
  57759. };
  57760. // Creates and populates the heightMap array with "facet" elements :
  57761. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  57762. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57763. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57764. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57765. // Returns the GroundMesh.
  57766. GroundMesh.prototype._initHeightQuads = function () {
  57767. var subdivisionsX = this._subdivisionsX;
  57768. var subdivisionsY = this._subdivisionsY;
  57769. this._heightQuads = new Array();
  57770. for (var row = 0; row < subdivisionsY; row++) {
  57771. for (var col = 0; col < subdivisionsX; col++) {
  57772. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  57773. this._heightQuads[row * subdivisionsX + col] = quad;
  57774. }
  57775. }
  57776. return this;
  57777. };
  57778. // Compute each quad element values and update the the heightMap array :
  57779. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57780. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57781. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57782. // Returns the GroundMesh.
  57783. GroundMesh.prototype._computeHeightQuads = function () {
  57784. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57785. if (!positions) {
  57786. return this;
  57787. }
  57788. var v1 = BABYLON.Tmp.Vector3[3];
  57789. var v2 = BABYLON.Tmp.Vector3[2];
  57790. var v3 = BABYLON.Tmp.Vector3[1];
  57791. var v4 = BABYLON.Tmp.Vector3[0];
  57792. var v1v2 = BABYLON.Tmp.Vector3[4];
  57793. var v1v3 = BABYLON.Tmp.Vector3[5];
  57794. var v1v4 = BABYLON.Tmp.Vector3[6];
  57795. var norm1 = BABYLON.Tmp.Vector3[7];
  57796. var norm2 = BABYLON.Tmp.Vector3[8];
  57797. var i = 0;
  57798. var j = 0;
  57799. var k = 0;
  57800. var cd = 0; // 2D slope coefficient : z = cd * x + h
  57801. var h = 0;
  57802. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  57803. var d2 = 0;
  57804. var subdivisionsX = this._subdivisionsX;
  57805. var subdivisionsY = this._subdivisionsY;
  57806. for (var row = 0; row < subdivisionsY; row++) {
  57807. for (var col = 0; col < subdivisionsX; col++) {
  57808. i = col * 3;
  57809. j = row * (subdivisionsX + 1) * 3;
  57810. k = (row + 1) * (subdivisionsX + 1) * 3;
  57811. v1.x = positions[j + i];
  57812. v1.y = positions[j + i + 1];
  57813. v1.z = positions[j + i + 2];
  57814. v2.x = positions[j + i + 3];
  57815. v2.y = positions[j + i + 4];
  57816. v2.z = positions[j + i + 5];
  57817. v3.x = positions[k + i];
  57818. v3.y = positions[k + i + 1];
  57819. v3.z = positions[k + i + 2];
  57820. v4.x = positions[k + i + 3];
  57821. v4.y = positions[k + i + 4];
  57822. v4.z = positions[k + i + 5];
  57823. // 2D slope V1V4
  57824. cd = (v4.z - v1.z) / (v4.x - v1.x);
  57825. h = v1.z - cd * v1.x; // v1 belongs to the slope
  57826. // facet equations :
  57827. // we compute each facet normal vector
  57828. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  57829. // we compute the value d by applying the equation to v1 which belongs to the plane
  57830. // then we store the facet equation in a Vector4
  57831. v2.subtractToRef(v1, v1v2);
  57832. v3.subtractToRef(v1, v1v3);
  57833. v4.subtractToRef(v1, v1v4);
  57834. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  57835. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  57836. norm1.normalize();
  57837. norm2.normalize();
  57838. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  57839. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  57840. var quad = this._heightQuads[row * subdivisionsX + col];
  57841. quad.slope.copyFromFloats(cd, h);
  57842. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  57843. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  57844. }
  57845. }
  57846. return this;
  57847. };
  57848. GroundMesh.prototype.serialize = function (serializationObject) {
  57849. _super.prototype.serialize.call(this, serializationObject);
  57850. serializationObject.subdivisionsX = this._subdivisionsX;
  57851. serializationObject.subdivisionsY = this._subdivisionsY;
  57852. serializationObject.minX = this._minX;
  57853. serializationObject.maxX = this._maxX;
  57854. serializationObject.minZ = this._minZ;
  57855. serializationObject.maxZ = this._maxZ;
  57856. serializationObject.width = this._width;
  57857. serializationObject.height = this._height;
  57858. };
  57859. GroundMesh.Parse = function (parsedMesh, scene) {
  57860. var result = new GroundMesh(parsedMesh.name, scene);
  57861. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  57862. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  57863. result._minX = parsedMesh.minX;
  57864. result._maxX = parsedMesh.maxX;
  57865. result._minZ = parsedMesh.minZ;
  57866. result._maxZ = parsedMesh.maxZ;
  57867. result._width = parsedMesh.width;
  57868. result._height = parsedMesh.height;
  57869. return result;
  57870. };
  57871. return GroundMesh;
  57872. }(BABYLON.Mesh));
  57873. BABYLON.GroundMesh = GroundMesh;
  57874. })(BABYLON || (BABYLON = {}));
  57875. //# sourceMappingURL=babylon.groundMesh.js.map
  57876. var BABYLON;
  57877. (function (BABYLON) {
  57878. /**
  57879. * Creates an instance based on a source mesh.
  57880. */
  57881. var InstancedMesh = /** @class */ (function (_super) {
  57882. __extends(InstancedMesh, _super);
  57883. function InstancedMesh(name, source) {
  57884. var _this = _super.call(this, name, source.getScene()) || this;
  57885. source.instances.push(_this);
  57886. _this._sourceMesh = source;
  57887. _this.position.copyFrom(source.position);
  57888. _this.rotation.copyFrom(source.rotation);
  57889. _this.scaling.copyFrom(source.scaling);
  57890. if (source.rotationQuaternion) {
  57891. _this.rotationQuaternion = source.rotationQuaternion.clone();
  57892. }
  57893. _this.infiniteDistance = source.infiniteDistance;
  57894. _this.setPivotMatrix(source.getPivotMatrix());
  57895. _this.refreshBoundingInfo();
  57896. _this._syncSubMeshes();
  57897. return _this;
  57898. }
  57899. /**
  57900. * Returns the string "InstancedMesh".
  57901. */
  57902. InstancedMesh.prototype.getClassName = function () {
  57903. return "InstancedMesh";
  57904. };
  57905. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  57906. // Methods
  57907. get: function () {
  57908. return this._sourceMesh.receiveShadows;
  57909. },
  57910. enumerable: true,
  57911. configurable: true
  57912. });
  57913. Object.defineProperty(InstancedMesh.prototype, "material", {
  57914. get: function () {
  57915. return this._sourceMesh.material;
  57916. },
  57917. enumerable: true,
  57918. configurable: true
  57919. });
  57920. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  57921. get: function () {
  57922. return this._sourceMesh.visibility;
  57923. },
  57924. enumerable: true,
  57925. configurable: true
  57926. });
  57927. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  57928. get: function () {
  57929. return this._sourceMesh.skeleton;
  57930. },
  57931. enumerable: true,
  57932. configurable: true
  57933. });
  57934. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  57935. get: function () {
  57936. return this._sourceMesh.renderingGroupId;
  57937. },
  57938. set: function (value) {
  57939. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  57940. return;
  57941. }
  57942. //no-op with warning
  57943. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  57944. },
  57945. enumerable: true,
  57946. configurable: true
  57947. });
  57948. /**
  57949. * Returns the total number of vertices (integer).
  57950. */
  57951. InstancedMesh.prototype.getTotalVertices = function () {
  57952. return this._sourceMesh.getTotalVertices();
  57953. };
  57954. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  57955. get: function () {
  57956. return this._sourceMesh;
  57957. },
  57958. enumerable: true,
  57959. configurable: true
  57960. });
  57961. /**
  57962. * Is this node ready to be used/rendered
  57963. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  57964. * @return {boolean} is it ready
  57965. */
  57966. InstancedMesh.prototype.isReady = function (completeCheck) {
  57967. if (completeCheck === void 0) { completeCheck = false; }
  57968. return this._sourceMesh.isReady(completeCheck, true);
  57969. };
  57970. /**
  57971. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  57972. */
  57973. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  57974. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  57975. };
  57976. /**
  57977. * Sets the vertex data of the mesh geometry for the requested `kind`.
  57978. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  57979. * The `data` are either a numeric array either a Float32Array.
  57980. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  57981. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  57982. * Note that a new underlying VertexBuffer object is created each call.
  57983. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  57984. *
  57985. * Possible `kind` values :
  57986. * - BABYLON.VertexBuffer.PositionKind
  57987. * - BABYLON.VertexBuffer.UVKind
  57988. * - BABYLON.VertexBuffer.UV2Kind
  57989. * - BABYLON.VertexBuffer.UV3Kind
  57990. * - BABYLON.VertexBuffer.UV4Kind
  57991. * - BABYLON.VertexBuffer.UV5Kind
  57992. * - BABYLON.VertexBuffer.UV6Kind
  57993. * - BABYLON.VertexBuffer.ColorKind
  57994. * - BABYLON.VertexBuffer.MatricesIndicesKind
  57995. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  57996. * - BABYLON.VertexBuffer.MatricesWeightsKind
  57997. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  57998. *
  57999. * Returns the Mesh.
  58000. */
  58001. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58002. if (this.sourceMesh) {
  58003. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58004. }
  58005. return this.sourceMesh;
  58006. };
  58007. /**
  58008. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58009. * If the mesh has no geometry, it is simply returned as it is.
  58010. * The `data` are either a numeric array either a Float32Array.
  58011. * No new underlying VertexBuffer object is created.
  58012. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58013. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58014. *
  58015. * Possible `kind` values :
  58016. * - BABYLON.VertexBuffer.PositionKind
  58017. * - BABYLON.VertexBuffer.UVKind
  58018. * - BABYLON.VertexBuffer.UV2Kind
  58019. * - BABYLON.VertexBuffer.UV3Kind
  58020. * - BABYLON.VertexBuffer.UV4Kind
  58021. * - BABYLON.VertexBuffer.UV5Kind
  58022. * - BABYLON.VertexBuffer.UV6Kind
  58023. * - BABYLON.VertexBuffer.ColorKind
  58024. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58025. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58026. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58027. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58028. *
  58029. * Returns the Mesh.
  58030. */
  58031. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58032. if (this.sourceMesh) {
  58033. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58034. }
  58035. return this.sourceMesh;
  58036. };
  58037. /**
  58038. * Sets the mesh indices.
  58039. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58040. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58041. * This method creates a new index buffer each call.
  58042. * Returns the Mesh.
  58043. */
  58044. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58045. if (totalVertices === void 0) { totalVertices = null; }
  58046. if (this.sourceMesh) {
  58047. this.sourceMesh.setIndices(indices, totalVertices);
  58048. }
  58049. return this.sourceMesh;
  58050. };
  58051. /**
  58052. * Boolean : True if the mesh owns the requested kind of data.
  58053. */
  58054. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58055. return this._sourceMesh.isVerticesDataPresent(kind);
  58056. };
  58057. /**
  58058. * Returns an array of indices (IndicesArray).
  58059. */
  58060. InstancedMesh.prototype.getIndices = function () {
  58061. return this._sourceMesh.getIndices();
  58062. };
  58063. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58064. get: function () {
  58065. return this._sourceMesh._positions;
  58066. },
  58067. enumerable: true,
  58068. configurable: true
  58069. });
  58070. /**
  58071. * Sets a new updated BoundingInfo to the mesh.
  58072. * Returns the mesh.
  58073. */
  58074. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58075. var meshBB = this._sourceMesh.getBoundingInfo();
  58076. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58077. this._updateBoundingInfo();
  58078. return this;
  58079. };
  58080. InstancedMesh.prototype._preActivate = function () {
  58081. if (this._currentLOD) {
  58082. this._currentLOD._preActivate();
  58083. }
  58084. return this;
  58085. };
  58086. InstancedMesh.prototype._activate = function (renderId) {
  58087. if (this._currentLOD) {
  58088. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58089. }
  58090. return this;
  58091. };
  58092. /**
  58093. * Returns the current associated LOD AbstractMesh.
  58094. */
  58095. InstancedMesh.prototype.getLOD = function (camera) {
  58096. if (!camera) {
  58097. return this;
  58098. }
  58099. var boundingInfo = this.getBoundingInfo();
  58100. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58101. if (this._currentLOD === this.sourceMesh) {
  58102. return this;
  58103. }
  58104. return this._currentLOD;
  58105. };
  58106. InstancedMesh.prototype._syncSubMeshes = function () {
  58107. this.releaseSubMeshes();
  58108. if (this._sourceMesh.subMeshes) {
  58109. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58110. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58111. }
  58112. }
  58113. return this;
  58114. };
  58115. InstancedMesh.prototype._generatePointsArray = function () {
  58116. return this._sourceMesh._generatePointsArray();
  58117. };
  58118. /**
  58119. * Creates a new InstancedMesh from the current mesh.
  58120. * - name (string) : the cloned mesh name
  58121. * - newParent (optional Node) : the optional Node to parent the clone to.
  58122. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58123. *
  58124. * Returns the clone.
  58125. */
  58126. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58127. var result = this._sourceMesh.createInstance(name);
  58128. // Deep copy
  58129. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58130. // Bounding info
  58131. this.refreshBoundingInfo();
  58132. // Parent
  58133. if (newParent) {
  58134. result.parent = newParent;
  58135. }
  58136. if (!doNotCloneChildren) {
  58137. // Children
  58138. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58139. var mesh = this.getScene().meshes[index];
  58140. if (mesh.parent === this) {
  58141. mesh.clone(mesh.name, result);
  58142. }
  58143. }
  58144. }
  58145. result.computeWorldMatrix(true);
  58146. return result;
  58147. };
  58148. /**
  58149. * Disposes the InstancedMesh.
  58150. * Returns nothing.
  58151. */
  58152. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58153. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58154. // Remove from mesh
  58155. var index = this._sourceMesh.instances.indexOf(this);
  58156. this._sourceMesh.instances.splice(index, 1);
  58157. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58158. };
  58159. return InstancedMesh;
  58160. }(BABYLON.AbstractMesh));
  58161. BABYLON.InstancedMesh = InstancedMesh;
  58162. })(BABYLON || (BABYLON = {}));
  58163. //# sourceMappingURL=babylon.instancedMesh.js.map
  58164. var BABYLON;
  58165. (function (BABYLON) {
  58166. var LinesMesh = /** @class */ (function (_super) {
  58167. __extends(LinesMesh, _super);
  58168. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58169. if (scene === void 0) { scene = null; }
  58170. if (parent === void 0) { parent = null; }
  58171. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58172. _this.useVertexColor = useVertexColor;
  58173. _this.useVertexAlpha = useVertexAlpha;
  58174. _this.color = new BABYLON.Color3(1, 1, 1);
  58175. _this.alpha = 1;
  58176. if (source) {
  58177. _this.color = source.color.clone();
  58178. _this.alpha = source.alpha;
  58179. _this.useVertexColor = source.useVertexColor;
  58180. _this.useVertexAlpha = source.useVertexAlpha;
  58181. }
  58182. _this._intersectionThreshold = 0.1;
  58183. var defines = [];
  58184. var options = {
  58185. attributes: [BABYLON.VertexBuffer.PositionKind],
  58186. uniforms: ["world", "viewProjection"],
  58187. needAlphaBlending: true,
  58188. defines: defines
  58189. };
  58190. if (useVertexAlpha === false) {
  58191. options.needAlphaBlending = false;
  58192. }
  58193. if (!useVertexColor) {
  58194. options.uniforms.push("color");
  58195. }
  58196. else {
  58197. options.defines.push("#define VERTEXCOLOR");
  58198. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58199. }
  58200. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58201. return _this;
  58202. }
  58203. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58204. /**
  58205. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58206. * This margin is expressed in world space coordinates, so its value may vary.
  58207. * Default value is 0.1
  58208. * @returns the intersection Threshold value.
  58209. */
  58210. get: function () {
  58211. return this._intersectionThreshold;
  58212. },
  58213. /**
  58214. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58215. * This margin is expressed in world space coordinates, so its value may vary.
  58216. * @param value the new threshold to apply
  58217. */
  58218. set: function (value) {
  58219. if (this._intersectionThreshold === value) {
  58220. return;
  58221. }
  58222. this._intersectionThreshold = value;
  58223. if (this.geometry) {
  58224. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58225. }
  58226. },
  58227. enumerable: true,
  58228. configurable: true
  58229. });
  58230. /**
  58231. * Returns the string "LineMesh"
  58232. */
  58233. LinesMesh.prototype.getClassName = function () {
  58234. return "LinesMesh";
  58235. };
  58236. Object.defineProperty(LinesMesh.prototype, "material", {
  58237. /**
  58238. * @hidden
  58239. */
  58240. get: function () {
  58241. return this._colorShader;
  58242. },
  58243. /**
  58244. * @hidden
  58245. */
  58246. set: function (value) {
  58247. // Do nothing
  58248. },
  58249. enumerable: true,
  58250. configurable: true
  58251. });
  58252. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58253. /**
  58254. * @hidden
  58255. */
  58256. get: function () {
  58257. return false;
  58258. },
  58259. enumerable: true,
  58260. configurable: true
  58261. });
  58262. LinesMesh.prototype.createInstance = function (name) {
  58263. throw new Error("LinesMeshes do not support createInstance.");
  58264. };
  58265. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58266. if (!this._geometry) {
  58267. return this;
  58268. }
  58269. // VBOs
  58270. this._geometry._bind(this._colorShader.getEffect());
  58271. // Color
  58272. if (!this.useVertexColor) {
  58273. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58274. }
  58275. return this;
  58276. };
  58277. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58278. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58279. return this;
  58280. }
  58281. var engine = this.getScene().getEngine();
  58282. // Draw order
  58283. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58284. return this;
  58285. };
  58286. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58287. this._colorShader.dispose();
  58288. _super.prototype.dispose.call(this, doNotRecurse);
  58289. };
  58290. /**
  58291. * Returns a new LineMesh object cloned from the current one.
  58292. */
  58293. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58294. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58295. };
  58296. return LinesMesh;
  58297. }(BABYLON.Mesh));
  58298. BABYLON.LinesMesh = LinesMesh;
  58299. })(BABYLON || (BABYLON = {}));
  58300. //# sourceMappingURL=babylon.linesMesh.js.map
  58301. var BABYLON;
  58302. (function (BABYLON) {
  58303. /**
  58304. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58305. * The underlying implementation relies on an associative array to ensure the best performances.
  58306. * The value can be anything including 'null' but except 'undefined'
  58307. */
  58308. var StringDictionary = /** @class */ (function () {
  58309. function StringDictionary() {
  58310. this._count = 0;
  58311. this._data = {};
  58312. }
  58313. /**
  58314. * This will clear this dictionary and copy the content from the 'source' one.
  58315. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58316. * @param source the dictionary to take the content from and copy to this dictionary
  58317. */
  58318. StringDictionary.prototype.copyFrom = function (source) {
  58319. var _this = this;
  58320. this.clear();
  58321. source.forEach(function (t, v) { return _this.add(t, v); });
  58322. };
  58323. /**
  58324. * Get a value based from its key
  58325. * @param key the given key to get the matching value from
  58326. * @return the value if found, otherwise undefined is returned
  58327. */
  58328. StringDictionary.prototype.get = function (key) {
  58329. var val = this._data[key];
  58330. if (val !== undefined) {
  58331. return val;
  58332. }
  58333. return undefined;
  58334. };
  58335. /**
  58336. * Get a value from its key or add it if it doesn't exist.
  58337. * This method will ensure you that a given key/data will be present in the dictionary.
  58338. * @param key the given key to get the matching value from
  58339. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58340. * The factory will only be invoked if there's no data for the given key.
  58341. * @return the value corresponding to the key.
  58342. */
  58343. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58344. var val = this.get(key);
  58345. if (val !== undefined) {
  58346. return val;
  58347. }
  58348. val = factory(key);
  58349. if (val) {
  58350. this.add(key, val);
  58351. }
  58352. return val;
  58353. };
  58354. /**
  58355. * Get a value from its key if present in the dictionary otherwise add it
  58356. * @param key the key to get the value from
  58357. * @param val if there's no such key/value pair in the dictionary add it with this value
  58358. * @return the value corresponding to the key
  58359. */
  58360. StringDictionary.prototype.getOrAdd = function (key, val) {
  58361. var curVal = this.get(key);
  58362. if (curVal !== undefined) {
  58363. return curVal;
  58364. }
  58365. this.add(key, val);
  58366. return val;
  58367. };
  58368. /**
  58369. * Check if there's a given key in the dictionary
  58370. * @param key the key to check for
  58371. * @return true if the key is present, false otherwise
  58372. */
  58373. StringDictionary.prototype.contains = function (key) {
  58374. return this._data[key] !== undefined;
  58375. };
  58376. /**
  58377. * Add a new key and its corresponding value
  58378. * @param key the key to add
  58379. * @param value the value corresponding to the key
  58380. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  58381. */
  58382. StringDictionary.prototype.add = function (key, value) {
  58383. if (this._data[key] !== undefined) {
  58384. return false;
  58385. }
  58386. this._data[key] = value;
  58387. ++this._count;
  58388. return true;
  58389. };
  58390. StringDictionary.prototype.set = function (key, value) {
  58391. if (this._data[key] === undefined) {
  58392. return false;
  58393. }
  58394. this._data[key] = value;
  58395. return true;
  58396. };
  58397. /**
  58398. * Get the element of the given key and remove it from the dictionary
  58399. * @param key
  58400. */
  58401. StringDictionary.prototype.getAndRemove = function (key) {
  58402. var val = this.get(key);
  58403. if (val !== undefined) {
  58404. delete this._data[key];
  58405. --this._count;
  58406. return val;
  58407. }
  58408. return null;
  58409. };
  58410. /**
  58411. * Remove a key/value from the dictionary.
  58412. * @param key the key to remove
  58413. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58414. */
  58415. StringDictionary.prototype.remove = function (key) {
  58416. if (this.contains(key)) {
  58417. delete this._data[key];
  58418. --this._count;
  58419. return true;
  58420. }
  58421. return false;
  58422. };
  58423. /**
  58424. * Clear the whole content of the dictionary
  58425. */
  58426. StringDictionary.prototype.clear = function () {
  58427. this._data = {};
  58428. this._count = 0;
  58429. };
  58430. Object.defineProperty(StringDictionary.prototype, "count", {
  58431. get: function () {
  58432. return this._count;
  58433. },
  58434. enumerable: true,
  58435. configurable: true
  58436. });
  58437. /**
  58438. * Execute a callback on each key/val of the dictionary.
  58439. * Note that you can remove any element in this dictionary in the callback implementation
  58440. * @param callback the callback to execute on a given key/value pair
  58441. */
  58442. StringDictionary.prototype.forEach = function (callback) {
  58443. for (var cur in this._data) {
  58444. var val = this._data[cur];
  58445. callback(cur, val);
  58446. }
  58447. };
  58448. /**
  58449. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58450. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58451. * Note that you can remove any element in this dictionary in the callback implementation
  58452. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58453. */
  58454. StringDictionary.prototype.first = function (callback) {
  58455. for (var cur in this._data) {
  58456. var val = this._data[cur];
  58457. var res = callback(cur, val);
  58458. if (res) {
  58459. return res;
  58460. }
  58461. }
  58462. return null;
  58463. };
  58464. return StringDictionary;
  58465. }());
  58466. BABYLON.StringDictionary = StringDictionary;
  58467. })(BABYLON || (BABYLON = {}));
  58468. //# sourceMappingURL=babylon.stringDictionary.js.map
  58469. var BABYLON;
  58470. (function (BABYLON) {
  58471. var Debug;
  58472. (function (Debug) {
  58473. /**
  58474. * Class used to render a debug view of a given skeleton
  58475. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  58476. */
  58477. var SkeletonViewer = /** @class */ (function () {
  58478. /**
  58479. * Creates a new SkeletonViewer
  58480. * @param skeleton defines the skeleton to render
  58481. * @param mesh defines the mesh attached to the skeleton
  58482. * @param scene defines the hosting scene
  58483. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  58484. * @param renderingGroupId defines the rendering group id to use with the viewer
  58485. */
  58486. function SkeletonViewer(
  58487. /** defines the skeleton to render */
  58488. skeleton,
  58489. /** defines the mesh attached to the skeleton */
  58490. mesh, scene,
  58491. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  58492. autoUpdateBonesMatrices,
  58493. /** defines the rendering group id to use with the viewer */
  58494. renderingGroupId) {
  58495. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58496. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58497. this.skeleton = skeleton;
  58498. this.mesh = mesh;
  58499. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58500. this.renderingGroupId = renderingGroupId;
  58501. /** Gets or sets the color used to render the skeleton */
  58502. this.color = BABYLON.Color3.White();
  58503. this._debugLines = new Array();
  58504. this._isEnabled = false;
  58505. this._scene = scene;
  58506. this.update();
  58507. this._renderFunction = this.update.bind(this);
  58508. }
  58509. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58510. get: function () {
  58511. return this._isEnabled;
  58512. },
  58513. /** Gets or sets a boolean indicating if the viewer is enabled */
  58514. set: function (value) {
  58515. if (this._isEnabled === value) {
  58516. return;
  58517. }
  58518. this._isEnabled = value;
  58519. if (value) {
  58520. this._scene.registerBeforeRender(this._renderFunction);
  58521. }
  58522. else {
  58523. this._scene.unregisterBeforeRender(this._renderFunction);
  58524. }
  58525. },
  58526. enumerable: true,
  58527. configurable: true
  58528. });
  58529. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58530. if (x === void 0) { x = 0; }
  58531. if (y === void 0) { y = 0; }
  58532. if (z === void 0) { z = 0; }
  58533. var tmat = BABYLON.Tmp.Matrix[0];
  58534. var parentBone = bone.getParent();
  58535. tmat.copyFrom(bone.getLocalMatrix());
  58536. if (x !== 0 || y !== 0 || z !== 0) {
  58537. var tmat2 = BABYLON.Tmp.Matrix[1];
  58538. BABYLON.Matrix.IdentityToRef(tmat2);
  58539. tmat2.m[12] = x;
  58540. tmat2.m[13] = y;
  58541. tmat2.m[14] = z;
  58542. tmat2.multiplyToRef(tmat, tmat);
  58543. }
  58544. if (parentBone) {
  58545. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58546. }
  58547. tmat.multiplyToRef(meshMat, tmat);
  58548. position.x = tmat.m[12];
  58549. position.y = tmat.m[13];
  58550. position.z = tmat.m[14];
  58551. };
  58552. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58553. var len = bones.length;
  58554. var meshPos = this.mesh.position;
  58555. for (var i = 0; i < len; i++) {
  58556. var bone = bones[i];
  58557. var points = this._debugLines[i];
  58558. if (!points) {
  58559. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58560. this._debugLines[i] = points;
  58561. }
  58562. this._getBonePosition(points[0], bone, meshMat);
  58563. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58564. points[0].subtractInPlace(meshPos);
  58565. points[1].subtractInPlace(meshPos);
  58566. }
  58567. };
  58568. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58569. var len = bones.length;
  58570. var boneNum = 0;
  58571. var meshPos = this.mesh.position;
  58572. for (var i = len - 1; i >= 0; i--) {
  58573. var childBone = bones[i];
  58574. var parentBone = childBone.getParent();
  58575. if (!parentBone) {
  58576. continue;
  58577. }
  58578. var points = this._debugLines[boneNum];
  58579. if (!points) {
  58580. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58581. this._debugLines[boneNum] = points;
  58582. }
  58583. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58584. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58585. points[0].subtractInPlace(meshPos);
  58586. points[1].subtractInPlace(meshPos);
  58587. boneNum++;
  58588. }
  58589. };
  58590. /** Update the viewer to sync with current skeleton state */
  58591. SkeletonViewer.prototype.update = function () {
  58592. if (this.autoUpdateBonesMatrices) {
  58593. this.skeleton.computeAbsoluteTransforms();
  58594. }
  58595. if (this.skeleton.bones[0].length === undefined) {
  58596. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58597. }
  58598. else {
  58599. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58600. }
  58601. if (!this._debugMesh) {
  58602. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  58603. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58604. }
  58605. else {
  58606. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58607. }
  58608. this._debugMesh.position.copyFrom(this.mesh.position);
  58609. this._debugMesh.color = this.color;
  58610. };
  58611. /** Release associated resources */
  58612. SkeletonViewer.prototype.dispose = function () {
  58613. if (this._debugMesh) {
  58614. this.isEnabled = false;
  58615. this._debugMesh.dispose();
  58616. this._debugMesh = null;
  58617. }
  58618. };
  58619. return SkeletonViewer;
  58620. }());
  58621. Debug.SkeletonViewer = SkeletonViewer;
  58622. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58623. })(BABYLON || (BABYLON = {}));
  58624. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58625. /**
  58626. * Module Debug contains the (visual) components to debug a scene correctly
  58627. */
  58628. var BABYLON;
  58629. (function (BABYLON) {
  58630. var Debug;
  58631. (function (Debug) {
  58632. /**
  58633. * The Axes viewer will show 3 axes in a specific point in space
  58634. */
  58635. var AxesViewer = /** @class */ (function () {
  58636. /**
  58637. * Creates a new AxesViewer
  58638. * @param scene defines the hosting scene
  58639. * @param scaleLines defines a number used to scale line length (1 by default)
  58640. */
  58641. function AxesViewer(scene, scaleLines) {
  58642. if (scaleLines === void 0) { scaleLines = 1; }
  58643. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58644. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58645. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58646. /**
  58647. * Gets or sets a number used to scale line length
  58648. */
  58649. this.scaleLines = 1;
  58650. this.scaleLines = scaleLines;
  58651. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58652. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58653. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58654. this._xmesh.renderingGroupId = 2;
  58655. this._ymesh.renderingGroupId = 2;
  58656. this._zmesh.renderingGroupId = 2;
  58657. this._xmesh.material.checkReadyOnlyOnce = true;
  58658. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58659. this._ymesh.material.checkReadyOnlyOnce = true;
  58660. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58661. this._zmesh.material.checkReadyOnlyOnce = true;
  58662. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58663. this.scene = scene;
  58664. }
  58665. /**
  58666. * Force the viewer to update
  58667. * @param position defines the position of the viewer
  58668. * @param xaxis defines the x axis of the viewer
  58669. * @param yaxis defines the y axis of the viewer
  58670. * @param zaxis defines the z axis of the viewer
  58671. */
  58672. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58673. var scaleLines = this.scaleLines;
  58674. if (this._xmesh) {
  58675. this._xmesh.position.copyFrom(position);
  58676. }
  58677. if (this._ymesh) {
  58678. this._ymesh.position.copyFrom(position);
  58679. }
  58680. if (this._zmesh) {
  58681. this._zmesh.position.copyFrom(position);
  58682. }
  58683. var point2 = this._xline[1];
  58684. point2.x = xaxis.x * scaleLines;
  58685. point2.y = xaxis.y * scaleLines;
  58686. point2.z = xaxis.z * scaleLines;
  58687. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  58688. point2 = this._yline[1];
  58689. point2.x = yaxis.x * scaleLines;
  58690. point2.y = yaxis.y * scaleLines;
  58691. point2.z = yaxis.z * scaleLines;
  58692. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  58693. point2 = this._zline[1];
  58694. point2.x = zaxis.x * scaleLines;
  58695. point2.y = zaxis.y * scaleLines;
  58696. point2.z = zaxis.z * scaleLines;
  58697. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  58698. };
  58699. /** Releases resources */
  58700. AxesViewer.prototype.dispose = function () {
  58701. if (this._xmesh) {
  58702. this._xmesh.dispose();
  58703. }
  58704. if (this._ymesh) {
  58705. this._ymesh.dispose();
  58706. }
  58707. if (this._zmesh) {
  58708. this._zmesh.dispose();
  58709. }
  58710. this._xmesh = null;
  58711. this._ymesh = null;
  58712. this._zmesh = null;
  58713. this.scene = null;
  58714. };
  58715. return AxesViewer;
  58716. }());
  58717. Debug.AxesViewer = AxesViewer;
  58718. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58719. })(BABYLON || (BABYLON = {}));
  58720. //# sourceMappingURL=babylon.axesViewer.js.map
  58721. var BABYLON;
  58722. (function (BABYLON) {
  58723. var Debug;
  58724. (function (Debug) {
  58725. /**
  58726. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  58727. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  58728. */
  58729. var BoneAxesViewer = /** @class */ (function (_super) {
  58730. __extends(BoneAxesViewer, _super);
  58731. /**
  58732. * Creates a new BoneAxesViewer
  58733. * @param scene defines the hosting scene
  58734. * @param bone defines the target bone
  58735. * @param mesh defines the target mesh
  58736. * @param scaleLines defines a scaling factor for line length (1 by default)
  58737. */
  58738. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58739. if (scaleLines === void 0) { scaleLines = 1; }
  58740. var _this = _super.call(this, scene, scaleLines) || this;
  58741. /** Gets current position */
  58742. _this.pos = BABYLON.Vector3.Zero();
  58743. /** Gets direction of X axis */
  58744. _this.xaxis = BABYLON.Vector3.Zero();
  58745. /** Gets direction of Y axis */
  58746. _this.yaxis = BABYLON.Vector3.Zero();
  58747. /** Gets direction of Z axis */
  58748. _this.zaxis = BABYLON.Vector3.Zero();
  58749. _this.mesh = mesh;
  58750. _this.bone = bone;
  58751. return _this;
  58752. }
  58753. /**
  58754. * Force the viewer to update
  58755. */
  58756. BoneAxesViewer.prototype.update = function () {
  58757. if (!this.mesh || !this.bone) {
  58758. return;
  58759. }
  58760. var bone = this.bone;
  58761. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58762. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58763. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58764. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58765. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58766. };
  58767. /** Releases resources */
  58768. BoneAxesViewer.prototype.dispose = function () {
  58769. if (this.mesh) {
  58770. this.mesh = null;
  58771. this.bone = null;
  58772. _super.prototype.dispose.call(this);
  58773. }
  58774. };
  58775. return BoneAxesViewer;
  58776. }(Debug.AxesViewer));
  58777. Debug.BoneAxesViewer = BoneAxesViewer;
  58778. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58779. })(BABYLON || (BABYLON = {}));
  58780. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58781. var BABYLON;
  58782. (function (BABYLON) {
  58783. var RayHelper = /** @class */ (function () {
  58784. function RayHelper(ray) {
  58785. this.ray = ray;
  58786. }
  58787. RayHelper.CreateAndShow = function (ray, scene, color) {
  58788. var helper = new RayHelper(ray);
  58789. helper.show(scene, color);
  58790. return helper;
  58791. };
  58792. RayHelper.prototype.show = function (scene, color) {
  58793. if (!this._renderFunction && this.ray) {
  58794. var ray = this.ray;
  58795. this._renderFunction = this._render.bind(this);
  58796. this._scene = scene;
  58797. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  58798. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  58799. if (this._renderFunction) {
  58800. this._scene.registerBeforeRender(this._renderFunction);
  58801. }
  58802. }
  58803. if (color && this._renderLine) {
  58804. this._renderLine.color.copyFrom(color);
  58805. }
  58806. };
  58807. RayHelper.prototype.hide = function () {
  58808. if (this._renderFunction && this._scene) {
  58809. this._scene.unregisterBeforeRender(this._renderFunction);
  58810. this._scene = null;
  58811. this._renderFunction = null;
  58812. if (this._renderLine) {
  58813. this._renderLine.dispose();
  58814. this._renderLine = null;
  58815. }
  58816. this._renderPoints = [];
  58817. }
  58818. };
  58819. RayHelper.prototype._render = function () {
  58820. var ray = this.ray;
  58821. if (!ray) {
  58822. return;
  58823. }
  58824. var point = this._renderPoints[1];
  58825. var len = Math.min(ray.length, 1000000);
  58826. point.copyFrom(ray.direction);
  58827. point.scaleInPlace(len);
  58828. point.addInPlace(ray.origin);
  58829. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  58830. };
  58831. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  58832. this._attachedToMesh = mesh;
  58833. var ray = this.ray;
  58834. if (!ray) {
  58835. return;
  58836. }
  58837. if (!ray.direction) {
  58838. ray.direction = BABYLON.Vector3.Zero();
  58839. }
  58840. if (!ray.origin) {
  58841. ray.origin = BABYLON.Vector3.Zero();
  58842. }
  58843. if (length) {
  58844. ray.length = length;
  58845. }
  58846. if (!meshSpaceOrigin) {
  58847. meshSpaceOrigin = BABYLON.Vector3.Zero();
  58848. }
  58849. if (!meshSpaceDirection) {
  58850. // -1 so that this will work with Mesh.lookAt
  58851. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  58852. }
  58853. if (!this._meshSpaceDirection) {
  58854. this._meshSpaceDirection = meshSpaceDirection.clone();
  58855. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  58856. }
  58857. else {
  58858. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  58859. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  58860. }
  58861. if (!this._updateToMeshFunction) {
  58862. this._updateToMeshFunction = this._updateToMesh.bind(this);
  58863. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  58864. }
  58865. this._updateToMesh();
  58866. };
  58867. RayHelper.prototype.detachFromMesh = function () {
  58868. if (this._attachedToMesh) {
  58869. if (this._updateToMeshFunction) {
  58870. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  58871. }
  58872. this._attachedToMesh = null;
  58873. this._updateToMeshFunction = null;
  58874. }
  58875. };
  58876. RayHelper.prototype._updateToMesh = function () {
  58877. var ray = this.ray;
  58878. if (!this._attachedToMesh || !ray) {
  58879. return;
  58880. }
  58881. if (this._attachedToMesh._isDisposed) {
  58882. this.detachFromMesh();
  58883. return;
  58884. }
  58885. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  58886. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  58887. };
  58888. RayHelper.prototype.dispose = function () {
  58889. this.hide();
  58890. this.detachFromMesh();
  58891. this.ray = null;
  58892. };
  58893. return RayHelper;
  58894. }());
  58895. BABYLON.RayHelper = RayHelper;
  58896. })(BABYLON || (BABYLON = {}));
  58897. //# sourceMappingURL=babylon.rayHelper.js.map
  58898. var BABYLON;
  58899. (function (BABYLON) {
  58900. // load the inspector using require, if not present in the global namespace.
  58901. var DebugLayer = /** @class */ (function () {
  58902. function DebugLayer(scene) {
  58903. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58904. this.onPropertyChangedObservable = new BABYLON.Observable();
  58905. this._scene = scene;
  58906. }
  58907. /** Creates the inspector window. */
  58908. DebugLayer.prototype._createInspector = function (config) {
  58909. if (config === void 0) { config = {}; }
  58910. var popup = config.popup || false;
  58911. var initialTab = config.initialTab || 0;
  58912. var parentElement = config.parentElement || null;
  58913. if (!this._inspector) {
  58914. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58915. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  58916. } // else nothing to do as instance is already created
  58917. };
  58918. DebugLayer.prototype.isVisible = function () {
  58919. if (!this._inspector) {
  58920. return false;
  58921. }
  58922. return true;
  58923. };
  58924. DebugLayer.prototype.hide = function () {
  58925. if (this._inspector) {
  58926. try {
  58927. this._inspector.dispose();
  58928. }
  58929. catch (e) {
  58930. // If the inspector has been removed directly from the inspector tool
  58931. }
  58932. this.onPropertyChangedObservable.clear();
  58933. this._inspector = null;
  58934. }
  58935. };
  58936. /**
  58937. *
  58938. * Launch the debugLayer.
  58939. *
  58940. * initialTab:
  58941. * | Value | Tab Name |
  58942. * | --- | --- |
  58943. * | 0 | Scene |
  58944. * | 1 | Console |
  58945. * | 2 | Stats |
  58946. * | 3 | Textures |
  58947. * | 4 | Mesh |
  58948. * | 5 | Light |
  58949. * | 6 | Material |
  58950. * | 7 | GLTF |
  58951. * | 8 | GUI |
  58952. * | 9 | Physics |
  58953. * | 10 | Camera |
  58954. * | 11 | Audio |
  58955. *
  58956. */
  58957. DebugLayer.prototype.show = function (config) {
  58958. if (config === void 0) { config = {}; }
  58959. if (typeof this.BJSINSPECTOR == 'undefined') {
  58960. // Load inspector and add it to the DOM
  58961. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  58962. }
  58963. else {
  58964. // Otherwise creates the inspector
  58965. this._createInspector(config);
  58966. }
  58967. };
  58968. /**
  58969. * Gets the active tab
  58970. * @return the index of the active tab or -1 if the inspector is hidden
  58971. */
  58972. DebugLayer.prototype.getActiveTab = function () {
  58973. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  58974. };
  58975. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  58976. return DebugLayer;
  58977. }());
  58978. BABYLON.DebugLayer = DebugLayer;
  58979. })(BABYLON || (BABYLON = {}));
  58980. //# sourceMappingURL=babylon.debugLayer.js.map
  58981. var BABYLON;
  58982. (function (BABYLON) {
  58983. var Debug;
  58984. (function (Debug) {
  58985. /**
  58986. * Used to show the physics impostor around the specific mesh
  58987. */
  58988. var PhysicsViewer = /** @class */ (function () {
  58989. /**
  58990. * Creates a new PhysicsViewer
  58991. * @param scene defines the hosting scene
  58992. */
  58993. function PhysicsViewer(scene) {
  58994. /** @hidden */
  58995. this._impostors = [];
  58996. /** @hidden */
  58997. this._meshes = [];
  58998. /** @hidden */
  58999. this._numMeshes = 0;
  59000. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59001. var physicEngine = this._scene.getPhysicsEngine();
  59002. if (physicEngine) {
  59003. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  59004. }
  59005. }
  59006. /** @hidden */
  59007. PhysicsViewer.prototype._updateDebugMeshes = function () {
  59008. var plugin = this._physicsEnginePlugin;
  59009. for (var i = 0; i < this._numMeshes; i++) {
  59010. var impostor = this._impostors[i];
  59011. if (!impostor) {
  59012. continue;
  59013. }
  59014. if (impostor.isDisposed) {
  59015. this.hideImpostor(this._impostors[i--]);
  59016. }
  59017. else {
  59018. var mesh = this._meshes[i];
  59019. if (mesh && plugin) {
  59020. plugin.syncMeshWithImpostor(mesh, impostor);
  59021. }
  59022. }
  59023. }
  59024. };
  59025. /**
  59026. * Renders a specified physic impostor
  59027. * @param impostor defines the impostor to render
  59028. */
  59029. PhysicsViewer.prototype.showImpostor = function (impostor) {
  59030. if (!this._scene) {
  59031. return;
  59032. }
  59033. for (var i = 0; i < this._numMeshes; i++) {
  59034. if (this._impostors[i] == impostor) {
  59035. return;
  59036. }
  59037. }
  59038. var debugMesh = this._getDebugMesh(impostor, this._scene);
  59039. if (debugMesh) {
  59040. this._impostors[this._numMeshes] = impostor;
  59041. this._meshes[this._numMeshes] = debugMesh;
  59042. if (this._numMeshes === 0) {
  59043. this._renderFunction = this._updateDebugMeshes.bind(this);
  59044. this._scene.registerBeforeRender(this._renderFunction);
  59045. }
  59046. this._numMeshes++;
  59047. }
  59048. };
  59049. /**
  59050. * Hides a specified physic impostor
  59051. * @param impostor defines the impostor to hide
  59052. */
  59053. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  59054. if (!impostor || !this._scene) {
  59055. return;
  59056. }
  59057. var removed = false;
  59058. for (var i = 0; i < this._numMeshes; i++) {
  59059. if (this._impostors[i] == impostor) {
  59060. var mesh = this._meshes[i];
  59061. if (!mesh) {
  59062. continue;
  59063. }
  59064. this._scene.removeMesh(mesh);
  59065. mesh.dispose();
  59066. this._numMeshes--;
  59067. if (this._numMeshes > 0) {
  59068. this._meshes[i] = this._meshes[this._numMeshes];
  59069. this._impostors[i] = this._impostors[this._numMeshes];
  59070. this._meshes[this._numMeshes] = null;
  59071. this._impostors[this._numMeshes] = null;
  59072. }
  59073. else {
  59074. this._meshes[0] = null;
  59075. this._impostors[0] = null;
  59076. }
  59077. removed = true;
  59078. break;
  59079. }
  59080. }
  59081. if (removed && this._numMeshes === 0) {
  59082. this._scene.unregisterBeforeRender(this._renderFunction);
  59083. }
  59084. };
  59085. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  59086. if (!this._debugMaterial) {
  59087. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59088. this._debugMaterial.wireframe = true;
  59089. }
  59090. return this._debugMaterial;
  59091. };
  59092. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  59093. if (!this._debugBoxMesh) {
  59094. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59095. this._debugBoxMesh.renderingGroupId = 1;
  59096. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59097. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59098. scene.removeMesh(this._debugBoxMesh);
  59099. }
  59100. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59101. };
  59102. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  59103. if (!this._debugSphereMesh) {
  59104. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59105. this._debugSphereMesh.renderingGroupId = 1;
  59106. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59107. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59108. scene.removeMesh(this._debugSphereMesh);
  59109. }
  59110. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59111. };
  59112. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  59113. var mesh = null;
  59114. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  59115. mesh = this._getDebugBoxMesh(scene);
  59116. impostor.getBoxSizeToRef(mesh.scaling);
  59117. }
  59118. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  59119. mesh = this._getDebugSphereMesh(scene);
  59120. var radius = impostor.getRadius();
  59121. mesh.scaling.x = radius * 2;
  59122. mesh.scaling.y = radius * 2;
  59123. mesh.scaling.z = radius * 2;
  59124. }
  59125. return mesh;
  59126. };
  59127. /** Releases all resources */
  59128. PhysicsViewer.prototype.dispose = function () {
  59129. for (var i = 0; i < this._numMeshes; i++) {
  59130. this.hideImpostor(this._impostors[i]);
  59131. }
  59132. if (this._debugBoxMesh) {
  59133. this._debugBoxMesh.dispose();
  59134. }
  59135. if (this._debugSphereMesh) {
  59136. this._debugSphereMesh.dispose();
  59137. }
  59138. if (this._debugMaterial) {
  59139. this._debugMaterial.dispose();
  59140. }
  59141. this._impostors.length = 0;
  59142. this._scene = null;
  59143. this._physicsEnginePlugin = null;
  59144. };
  59145. return PhysicsViewer;
  59146. }());
  59147. Debug.PhysicsViewer = PhysicsViewer;
  59148. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59149. })(BABYLON || (BABYLON = {}));
  59150. //# sourceMappingURL=babylon.physicsViewer.js.map
  59151. var BABYLON;
  59152. (function (BABYLON) {
  59153. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  59154. get: function () {
  59155. return this._forceShowBoundingBoxes || false;
  59156. },
  59157. set: function (value) {
  59158. this._forceShowBoundingBoxes = value;
  59159. // Lazyly creates a BB renderer if needed.
  59160. if (value) {
  59161. this.getBoundingBoxRenderer();
  59162. }
  59163. },
  59164. enumerable: true,
  59165. configurable: true
  59166. });
  59167. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  59168. if (!this._boundingBoxRenderer) {
  59169. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  59170. }
  59171. return this._boundingBoxRenderer;
  59172. };
  59173. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  59174. get: function () {
  59175. return this._showBoundingBox || false;
  59176. },
  59177. set: function (value) {
  59178. this._showBoundingBox = value;
  59179. // Lazyly creates a BB renderer if needed.
  59180. if (value) {
  59181. this.getScene().getBoundingBoxRenderer();
  59182. }
  59183. },
  59184. enumerable: true,
  59185. configurable: true
  59186. });
  59187. var BoundingBoxRenderer = /** @class */ (function () {
  59188. function BoundingBoxRenderer(scene) {
  59189. /**
  59190. * The component name helpfull to identify the component in the list of scene components.
  59191. */
  59192. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  59193. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59194. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59195. this.showBackLines = true;
  59196. this.renderList = new BABYLON.SmartArray(32);
  59197. this._vertexBuffers = {};
  59198. this.scene = scene;
  59199. scene._addComponent(this);
  59200. }
  59201. /**
  59202. * Registers the component in a given scene
  59203. */
  59204. BoundingBoxRenderer.prototype.register = function () {
  59205. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  59206. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  59207. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  59208. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  59209. };
  59210. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  59211. if (mesh.showSubMeshesBoundingBox) {
  59212. var boundingInfo = subMesh.getBoundingInfo();
  59213. if (boundingInfo !== null && boundingInfo !== undefined) {
  59214. this.renderList.push(boundingInfo.boundingBox);
  59215. }
  59216. }
  59217. };
  59218. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  59219. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  59220. var boundingInfo = sourceMesh.getBoundingInfo();
  59221. this.renderList.push(boundingInfo.boundingBox);
  59222. }
  59223. };
  59224. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59225. if (this._colorShader) {
  59226. return;
  59227. }
  59228. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  59229. attributes: [BABYLON.VertexBuffer.PositionKind],
  59230. uniforms: ["world", "viewProjection", "color"]
  59231. });
  59232. var engine = this.scene.getEngine();
  59233. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  59234. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59235. this._createIndexBuffer();
  59236. };
  59237. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  59238. var engine = this.scene.getEngine();
  59239. this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  59240. };
  59241. /**
  59242. * Rebuilds the elements related to this component in case of
  59243. * context lost for instance.
  59244. */
  59245. BoundingBoxRenderer.prototype.rebuild = function () {
  59246. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59247. if (vb) {
  59248. vb._rebuild();
  59249. }
  59250. this._createIndexBuffer();
  59251. };
  59252. BoundingBoxRenderer.prototype.reset = function () {
  59253. this.renderList.reset();
  59254. };
  59255. BoundingBoxRenderer.prototype.render = function () {
  59256. if (this.renderList.length === 0) {
  59257. return;
  59258. }
  59259. this._prepareRessources();
  59260. if (!this._colorShader.isReady()) {
  59261. return;
  59262. }
  59263. var engine = this.scene.getEngine();
  59264. engine.setDepthWrite(false);
  59265. this._colorShader._preBind();
  59266. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59267. var boundingBox = this.renderList.data[boundingBoxIndex];
  59268. var min = boundingBox.minimum;
  59269. var max = boundingBox.maximum;
  59270. var diff = max.subtract(min);
  59271. var median = min.add(diff.scale(0.5));
  59272. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59273. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59274. .multiply(boundingBox.getWorldMatrix());
  59275. // VBOs
  59276. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59277. if (this.showBackLines) {
  59278. // Back
  59279. engine.setDepthFunctionToGreaterOrEqual();
  59280. this.scene.resetCachedMaterial();
  59281. this._colorShader.setColor4("color", this.backColor.toColor4());
  59282. this._colorShader.bind(worldMatrix);
  59283. // Draw order
  59284. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59285. }
  59286. // Front
  59287. engine.setDepthFunctionToLess();
  59288. this.scene.resetCachedMaterial();
  59289. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59290. this._colorShader.bind(worldMatrix);
  59291. // Draw order
  59292. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59293. }
  59294. this._colorShader.unbind();
  59295. engine.setDepthFunctionToLessOrEqual();
  59296. engine.setDepthWrite(true);
  59297. };
  59298. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  59299. this._prepareRessources();
  59300. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  59301. return;
  59302. }
  59303. var engine = this.scene.getEngine();
  59304. engine.setDepthWrite(false);
  59305. engine.setColorWrite(false);
  59306. this._colorShader._preBind();
  59307. var boundingBox = mesh._boundingInfo.boundingBox;
  59308. var min = boundingBox.minimum;
  59309. var max = boundingBox.maximum;
  59310. var diff = max.subtract(min);
  59311. var median = min.add(diff.scale(0.5));
  59312. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59313. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59314. .multiply(boundingBox.getWorldMatrix());
  59315. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59316. engine.setDepthFunctionToLess();
  59317. this.scene.resetCachedMaterial();
  59318. this._colorShader.bind(worldMatrix);
  59319. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59320. this._colorShader.unbind();
  59321. engine.setDepthFunctionToLessOrEqual();
  59322. engine.setDepthWrite(true);
  59323. engine.setColorWrite(true);
  59324. };
  59325. BoundingBoxRenderer.prototype.dispose = function () {
  59326. if (!this._colorShader) {
  59327. return;
  59328. }
  59329. this.renderList.dispose();
  59330. this._colorShader.dispose();
  59331. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59332. if (buffer) {
  59333. buffer.dispose();
  59334. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59335. }
  59336. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  59337. };
  59338. return BoundingBoxRenderer;
  59339. }());
  59340. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59341. })(BABYLON || (BABYLON = {}));
  59342. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59343. var BABYLON;
  59344. (function (BABYLON) {
  59345. BABYLON.Engine.prototype.createTransformFeedback = function () {
  59346. return this._gl.createTransformFeedback();
  59347. };
  59348. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  59349. this._gl.deleteTransformFeedback(value);
  59350. };
  59351. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  59352. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  59353. };
  59354. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  59355. if (usePoints === void 0) { usePoints = true; }
  59356. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  59357. };
  59358. BABYLON.Engine.prototype.endTransformFeedback = function () {
  59359. this._gl.endTransformFeedback();
  59360. };
  59361. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  59362. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  59363. };
  59364. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  59365. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  59366. };
  59367. })(BABYLON || (BABYLON = {}));
  59368. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  59369. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59370. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59371. s = arguments[i];
  59372. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59373. t[p] = s[p];
  59374. }
  59375. return t;
  59376. };
  59377. var BABYLON;
  59378. (function (BABYLON) {
  59379. /**
  59380. * This represents a GPU particle system in Babylon
  59381. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  59382. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  59383. */
  59384. var GPUParticleSystem = /** @class */ (function () {
  59385. /**
  59386. * Instantiates a GPU particle system.
  59387. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  59388. * @param name The name of the particle system
  59389. * @param options The options used to create the system
  59390. * @param scene The scene the particle system belongs to
  59391. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59392. */
  59393. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  59394. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59395. /**
  59396. * The emitter represents the Mesh or position we are attaching the particle system to.
  59397. */
  59398. this.emitter = null;
  59399. /**
  59400. * The rendering group used by the Particle system to chose when to render.
  59401. */
  59402. this.renderingGroupId = 0;
  59403. /**
  59404. * The layer mask we are rendering the particles through.
  59405. */
  59406. this.layerMask = 0x0FFFFFFF;
  59407. this._accumulatedCount = 0;
  59408. this._targetIndex = 0;
  59409. this._currentRenderId = -1;
  59410. this._started = false;
  59411. this._stopped = false;
  59412. this._timeDelta = 0;
  59413. this._attributesStrideSize = 21;
  59414. this._actualFrame = 0;
  59415. this._rawTextureWidth = 256;
  59416. /**
  59417. * List of animations used by the particle system.
  59418. */
  59419. this.animations = [];
  59420. /**
  59421. * An event triggered when the system is disposed.
  59422. */
  59423. this.onDisposeObservable = new BABYLON.Observable();
  59424. /**
  59425. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59426. */
  59427. this.updateSpeed = 0.01;
  59428. /**
  59429. * The amount of time the particle system is running (depends of the overall update speed).
  59430. */
  59431. this.targetStopDuration = 0;
  59432. /**
  59433. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59434. */
  59435. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59436. /**
  59437. * Minimum life time of emitting particles.
  59438. */
  59439. this.minLifeTime = 1;
  59440. /**
  59441. * Maximum life time of emitting particles.
  59442. */
  59443. this.maxLifeTime = 1;
  59444. /**
  59445. * Minimum Size of emitting particles.
  59446. */
  59447. this.minSize = 1;
  59448. /**
  59449. * Maximum Size of emitting particles.
  59450. */
  59451. this.maxSize = 1;
  59452. /**
  59453. * Minimum scale of emitting particles on X axis.
  59454. */
  59455. this.minScaleX = 1;
  59456. /**
  59457. * Maximum scale of emitting particles on X axis.
  59458. */
  59459. this.maxScaleX = 1;
  59460. /**
  59461. * Minimum scale of emitting particles on Y axis.
  59462. */
  59463. this.minScaleY = 1;
  59464. /**
  59465. * Maximum scale of emitting particles on Y axis.
  59466. */
  59467. this.maxScaleY = 1;
  59468. /**
  59469. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59470. */
  59471. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59472. /**
  59473. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59474. */
  59475. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59476. /**
  59477. * Color the particle will have at the end of its lifetime.
  59478. */
  59479. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  59480. /**
  59481. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  59482. */
  59483. this.emitRate = 100;
  59484. /**
  59485. * You can use gravity if you want to give an orientation to your particles.
  59486. */
  59487. this.gravity = BABYLON.Vector3.Zero();
  59488. /**
  59489. * Minimum power of emitting particles.
  59490. */
  59491. this.minEmitPower = 1;
  59492. /**
  59493. * Maximum power of emitting particles.
  59494. */
  59495. this.maxEmitPower = 1;
  59496. /**
  59497. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59498. */
  59499. this.minAngularSpeed = 0;
  59500. /**
  59501. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59502. */
  59503. this.maxAngularSpeed = 0;
  59504. /**
  59505. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59506. * to override the particles.
  59507. */
  59508. this.forceDepthWrite = false;
  59509. this._preWarmDone = false;
  59510. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  59511. this.preWarmCycles = 0;
  59512. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59513. this.preWarmStepOffset = 1;
  59514. /**
  59515. * Gets or sets the minimal initial rotation in radians.
  59516. */
  59517. this.minInitialRotation = 0;
  59518. /**
  59519. * Gets or sets the maximal initial rotation in radians.
  59520. */
  59521. this.maxInitialRotation = 0;
  59522. /**
  59523. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  59524. */
  59525. this.spriteCellChangeSpeed = 1;
  59526. /**
  59527. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59528. */
  59529. this.startSpriteCellID = 0;
  59530. /**
  59531. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59532. */
  59533. this.endSpriteCellID = 0;
  59534. /**
  59535. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59536. */
  59537. this.spriteCellWidth = 0;
  59538. /**
  59539. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59540. */
  59541. this.spriteCellHeight = 0;
  59542. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59543. this.translationPivot = new BABYLON.Vector2(0, 0);
  59544. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59545. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59546. /**
  59547. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59548. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  59549. */
  59550. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59551. this._isBillboardBased = true;
  59552. this._colorGradients = null;
  59553. this._angularSpeedGradients = null;
  59554. this._sizeGradients = null;
  59555. this._velocityGradients = null;
  59556. this.id = name;
  59557. this.name = name;
  59558. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59559. this._engine = this._scene.getEngine();
  59560. if (!options.randomTextureSize) {
  59561. delete options.randomTextureSize;
  59562. }
  59563. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  59564. var optionsAsNumber = options;
  59565. if (isFinite(optionsAsNumber)) {
  59566. fullOptions.capacity = optionsAsNumber;
  59567. }
  59568. this._capacity = fullOptions.capacity;
  59569. this._activeCount = fullOptions.capacity;
  59570. this._currentActiveCount = 0;
  59571. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59572. this._scene.particleSystems.push(this);
  59573. this._updateEffectOptions = {
  59574. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  59575. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  59576. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  59577. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  59578. uniformBuffersNames: [],
  59579. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  59580. defines: "",
  59581. fallbacks: null,
  59582. onCompiled: null,
  59583. onError: null,
  59584. indexParameters: null,
  59585. maxSimultaneousLights: 0,
  59586. transformFeedbackVaryings: []
  59587. };
  59588. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59589. // Random data
  59590. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  59591. var d = [];
  59592. for (var i = 0; i < maxTextureSize; ++i) {
  59593. d.push(Math.random());
  59594. d.push(Math.random());
  59595. d.push(Math.random());
  59596. d.push(Math.random());
  59597. }
  59598. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  59599. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59600. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59601. d = [];
  59602. for (var i = 0; i < maxTextureSize; ++i) {
  59603. d.push(Math.random());
  59604. d.push(Math.random());
  59605. d.push(Math.random());
  59606. d.push(Math.random());
  59607. }
  59608. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  59609. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59610. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59611. this._randomTextureSize = maxTextureSize;
  59612. }
  59613. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  59614. /**
  59615. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  59616. */
  59617. get: function () {
  59618. if (!BABYLON.Engine.LastCreatedEngine) {
  59619. return false;
  59620. }
  59621. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  59622. },
  59623. enumerable: true,
  59624. configurable: true
  59625. });
  59626. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  59627. /**
  59628. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59629. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59630. */
  59631. get: function () {
  59632. if (this.particleEmitterType.direction1) {
  59633. return this.particleEmitterType.direction1;
  59634. }
  59635. return BABYLON.Vector3.Zero();
  59636. },
  59637. set: function (value) {
  59638. if (this.particleEmitterType.direction1) {
  59639. this.particleEmitterType.direction1 = value;
  59640. }
  59641. },
  59642. enumerable: true,
  59643. configurable: true
  59644. });
  59645. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  59646. /**
  59647. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59648. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59649. */
  59650. get: function () {
  59651. if (this.particleEmitterType.direction2) {
  59652. return this.particleEmitterType.direction2;
  59653. }
  59654. return BABYLON.Vector3.Zero();
  59655. },
  59656. set: function (value) {
  59657. if (this.particleEmitterType.direction2) {
  59658. this.particleEmitterType.direction2 = value;
  59659. }
  59660. },
  59661. enumerable: true,
  59662. configurable: true
  59663. });
  59664. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  59665. /**
  59666. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  59667. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59668. */
  59669. get: function () {
  59670. if (this.particleEmitterType.minEmitBox) {
  59671. return this.particleEmitterType.minEmitBox;
  59672. }
  59673. return BABYLON.Vector3.Zero();
  59674. },
  59675. set: function (value) {
  59676. if (this.particleEmitterType.minEmitBox) {
  59677. this.particleEmitterType.minEmitBox = value;
  59678. }
  59679. },
  59680. enumerable: true,
  59681. configurable: true
  59682. });
  59683. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  59684. /**
  59685. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  59686. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59687. */
  59688. get: function () {
  59689. if (this.particleEmitterType.maxEmitBox) {
  59690. return this.particleEmitterType.maxEmitBox;
  59691. }
  59692. return BABYLON.Vector3.Zero();
  59693. },
  59694. set: function (value) {
  59695. if (this.particleEmitterType.maxEmitBox) {
  59696. this.particleEmitterType.maxEmitBox = value;
  59697. }
  59698. },
  59699. enumerable: true,
  59700. configurable: true
  59701. });
  59702. /**
  59703. * Gets the maximum number of particles active at the same time.
  59704. * @returns The max number of active particles.
  59705. */
  59706. GPUParticleSystem.prototype.getCapacity = function () {
  59707. return this._capacity;
  59708. };
  59709. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  59710. /**
  59711. * Gets or set the number of active particles
  59712. */
  59713. get: function () {
  59714. return this._activeCount;
  59715. },
  59716. set: function (value) {
  59717. this._activeCount = Math.min(value, this._capacity);
  59718. },
  59719. enumerable: true,
  59720. configurable: true
  59721. });
  59722. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  59723. /**
  59724. * Gets whether an animation sprite sheet is enabled or not on the particle system
  59725. */
  59726. get: function () {
  59727. return this._isAnimationSheetEnabled;
  59728. },
  59729. enumerable: true,
  59730. configurable: true
  59731. });
  59732. /**
  59733. * Is this system ready to be used/rendered
  59734. * @return true if the system is ready
  59735. */
  59736. GPUParticleSystem.prototype.isReady = function () {
  59737. if (!this._updateEffect) {
  59738. this._recreateUpdateEffect();
  59739. this._recreateRenderEffect();
  59740. return false;
  59741. }
  59742. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59743. return false;
  59744. }
  59745. return true;
  59746. };
  59747. /**
  59748. * Gets Wether the system has been started.
  59749. * @returns True if it has been started, otherwise false.
  59750. */
  59751. GPUParticleSystem.prototype.isStarted = function () {
  59752. return this._started;
  59753. };
  59754. /**
  59755. * Starts the particle system and begins to emit
  59756. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  59757. */
  59758. GPUParticleSystem.prototype.start = function (delay) {
  59759. var _this = this;
  59760. if (delay === void 0) { delay = 0; }
  59761. if (delay) {
  59762. setTimeout(function () {
  59763. _this.start(0);
  59764. }, delay);
  59765. return;
  59766. }
  59767. this._started = true;
  59768. this._stopped = false;
  59769. this._preWarmDone = false;
  59770. };
  59771. /**
  59772. * Stops the particle system.
  59773. */
  59774. GPUParticleSystem.prototype.stop = function () {
  59775. this._stopped = true;
  59776. };
  59777. /**
  59778. * Remove all active particles
  59779. */
  59780. GPUParticleSystem.prototype.reset = function () {
  59781. this._releaseBuffers();
  59782. this._releaseVAOs();
  59783. this._currentActiveCount = 0;
  59784. this._targetIndex = 0;
  59785. };
  59786. /**
  59787. * Returns the string "GPUParticleSystem"
  59788. * @returns a string containing the class name
  59789. */
  59790. GPUParticleSystem.prototype.getClassName = function () {
  59791. return "GPUParticleSystem";
  59792. };
  59793. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  59794. /**
  59795. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  59796. */
  59797. get: function () {
  59798. return this._isBillboardBased;
  59799. },
  59800. set: function (value) {
  59801. if (this._isBillboardBased === value) {
  59802. return;
  59803. }
  59804. this._isBillboardBased = value;
  59805. this._releaseBuffers();
  59806. },
  59807. enumerable: true,
  59808. configurable: true
  59809. });
  59810. /**
  59811. * Gets the current list of color gradients.
  59812. * You must use addColorGradient and removeColorGradient to udpate this list
  59813. * @returns the list of color gradients
  59814. */
  59815. GPUParticleSystem.prototype.getColorGradients = function () {
  59816. return this._colorGradients;
  59817. };
  59818. /**
  59819. * Gets the current list of size gradients.
  59820. * You must use addSizeGradient and removeSizeGradient to udpate this list
  59821. * @returns the list of size gradients
  59822. */
  59823. GPUParticleSystem.prototype.getSizeGradients = function () {
  59824. return this._sizeGradients;
  59825. };
  59826. /**
  59827. * Gets the current list of angular speed gradients.
  59828. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  59829. * @returns the list of angular speed gradients
  59830. */
  59831. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  59832. return this._angularSpeedGradients;
  59833. };
  59834. /**
  59835. * Gets the current list of velocity gradients.
  59836. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  59837. * @returns the list of angular speed gradients
  59838. */
  59839. GPUParticleSystem.prototype.getVelocityGradients = function () {
  59840. return this._velocityGradients;
  59841. };
  59842. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  59843. if (!gradients) {
  59844. return this;
  59845. }
  59846. var index = 0;
  59847. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59848. var valueGradient = gradients_1[_i];
  59849. if (valueGradient.gradient === gradient) {
  59850. gradients.splice(index, 1);
  59851. break;
  59852. }
  59853. index++;
  59854. }
  59855. if (texture) {
  59856. texture.dispose();
  59857. }
  59858. this._releaseBuffers();
  59859. return this;
  59860. };
  59861. /**
  59862. * Adds a new color gradient
  59863. * @param gradient defines the gradient to use (between 0 and 1)
  59864. * @param color defines the color to affect to the specified gradient
  59865. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59866. * @returns the current particle system
  59867. */
  59868. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59869. if (!this._colorGradients) {
  59870. this._colorGradients = [];
  59871. }
  59872. var colorGradient = new BABYLON.ColorGradient();
  59873. colorGradient.gradient = gradient;
  59874. colorGradient.color1 = color1;
  59875. this._colorGradients.push(colorGradient);
  59876. this._colorGradients.sort(function (a, b) {
  59877. if (a.gradient < b.gradient) {
  59878. return -1;
  59879. }
  59880. else if (a.gradient > b.gradient) {
  59881. return 1;
  59882. }
  59883. return 0;
  59884. });
  59885. if (this._colorGradientsTexture) {
  59886. this._colorGradientsTexture.dispose();
  59887. this._colorGradientsTexture = null;
  59888. }
  59889. this._releaseBuffers();
  59890. return this;
  59891. };
  59892. /**
  59893. * Remove a specific color gradient
  59894. * @param gradient defines the gradient to remove
  59895. * @returns the current particle system
  59896. */
  59897. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  59898. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  59899. this._colorGradientsTexture = null;
  59900. return this;
  59901. };
  59902. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  59903. var valueGradient = new BABYLON.FactorGradient();
  59904. valueGradient.gradient = gradient;
  59905. valueGradient.factor1 = factor;
  59906. factorGradients.push(valueGradient);
  59907. factorGradients.sort(function (a, b) {
  59908. if (a.gradient < b.gradient) {
  59909. return -1;
  59910. }
  59911. else if (a.gradient > b.gradient) {
  59912. return 1;
  59913. }
  59914. return 0;
  59915. });
  59916. this._releaseBuffers();
  59917. };
  59918. /**
  59919. * Adds a new size gradient
  59920. * @param gradient defines the gradient to use (between 0 and 1)
  59921. * @param factor defines the size factor to affect to the specified gradient
  59922. * @returns the current particle system
  59923. */
  59924. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  59925. if (!this._sizeGradients) {
  59926. this._sizeGradients = [];
  59927. }
  59928. this._addFactorGradient(this._sizeGradients, gradient, factor);
  59929. if (this._sizeGradientsTexture) {
  59930. this._sizeGradientsTexture.dispose();
  59931. this._sizeGradientsTexture = null;
  59932. }
  59933. this._releaseBuffers();
  59934. return this;
  59935. };
  59936. /**
  59937. * Remove a specific size gradient
  59938. * @param gradient defines the gradient to remove
  59939. * @returns the current particle system
  59940. */
  59941. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59942. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  59943. this._sizeGradientsTexture = null;
  59944. return this;
  59945. };
  59946. /**
  59947. * Adds a new angular speed gradient
  59948. * @param gradient defines the gradient to use (between 0 and 1)
  59949. * @param factor defines the size factor to affect to the specified gradient
  59950. * @returns the current particle system
  59951. */
  59952. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  59953. if (!this._angularSpeedGradients) {
  59954. this._angularSpeedGradients = [];
  59955. }
  59956. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  59957. if (this._angularSpeedGradientsTexture) {
  59958. this._angularSpeedGradientsTexture.dispose();
  59959. this._angularSpeedGradientsTexture = null;
  59960. }
  59961. this._releaseBuffers();
  59962. return this;
  59963. };
  59964. /**
  59965. * Remove a specific angular speed gradient
  59966. * @param gradient defines the gradient to remove
  59967. * @returns the current particle system
  59968. */
  59969. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59970. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  59971. this._angularSpeedGradientsTexture = null;
  59972. return this;
  59973. };
  59974. /**
  59975. * Adds a new velocity gradient
  59976. * @param gradient defines the gradient to use (between 0 and 1)
  59977. * @param factor defines the size factor to affect to the specified gradient
  59978. * @returns the current particle system
  59979. */
  59980. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  59981. if (!this._velocityGradients) {
  59982. this._velocityGradients = [];
  59983. }
  59984. this._addFactorGradient(this._velocityGradients, gradient, factor);
  59985. if (this._velocityGradientsTexture) {
  59986. this._velocityGradientsTexture.dispose();
  59987. this._velocityGradientsTexture = null;
  59988. }
  59989. this._releaseBuffers();
  59990. return this;
  59991. };
  59992. /**
  59993. * Remove a specific velocity gradient
  59994. * @param gradient defines the gradient to remove
  59995. * @returns the current particle system
  59996. */
  59997. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59998. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  59999. this._velocityGradientsTexture = null;
  60000. return this;
  60001. };
  60002. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60003. var updateVertexBuffers = {};
  60004. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60005. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60006. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60007. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60008. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60009. var offset = 12;
  60010. if (!this._colorGradientsTexture) {
  60011. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60012. offset += 4;
  60013. }
  60014. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60015. offset += 3;
  60016. if (!this._isBillboardBased) {
  60017. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60018. offset += 3;
  60019. }
  60020. if (this._angularSpeedGradientsTexture) {
  60021. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60022. offset += 1;
  60023. }
  60024. else {
  60025. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60026. offset += 2;
  60027. }
  60028. if (this._isAnimationSheetEnabled) {
  60029. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60030. offset += 1;
  60031. }
  60032. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60033. this._engine.bindArrayBuffer(null);
  60034. return vao;
  60035. };
  60036. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60037. var renderVertexBuffers = {};
  60038. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60039. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60040. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60041. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60042. var offset = 12;
  60043. if (!this._colorGradientsTexture) {
  60044. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60045. offset += 4;
  60046. }
  60047. offset += 3; // Direction
  60048. if (!this._isBillboardBased) {
  60049. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60050. offset += 3;
  60051. }
  60052. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60053. if (this._angularSpeedGradientsTexture) {
  60054. offset++;
  60055. }
  60056. else {
  60057. offset += 2;
  60058. }
  60059. if (this._isAnimationSheetEnabled) {
  60060. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60061. offset += 1;
  60062. }
  60063. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60064. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60065. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60066. this._engine.bindArrayBuffer(null);
  60067. return vao;
  60068. };
  60069. GPUParticleSystem.prototype._initialize = function (force) {
  60070. if (force === void 0) { force = false; }
  60071. if (this._buffer0 && !force) {
  60072. return;
  60073. }
  60074. var engine = this._scene.getEngine();
  60075. var data = new Array();
  60076. if (!this.isBillboardBased) {
  60077. this._attributesStrideSize += 3;
  60078. }
  60079. if (this._colorGradientsTexture) {
  60080. this._attributesStrideSize -= 4;
  60081. }
  60082. if (this._angularSpeedGradientsTexture) {
  60083. this._attributesStrideSize -= 1;
  60084. }
  60085. if (this._isAnimationSheetEnabled) {
  60086. this._attributesStrideSize += 1;
  60087. }
  60088. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60089. // position
  60090. data.push(0.0);
  60091. data.push(0.0);
  60092. data.push(0.0);
  60093. // Age and life
  60094. data.push(0.0); // create the particle as a dead one to create a new one at start
  60095. data.push(0.0);
  60096. // Seed
  60097. data.push(Math.random());
  60098. data.push(Math.random());
  60099. data.push(Math.random());
  60100. data.push(Math.random());
  60101. // Size
  60102. data.push(0.0);
  60103. data.push(0.0);
  60104. data.push(0.0);
  60105. if (!this._colorGradientsTexture) {
  60106. // color
  60107. data.push(0.0);
  60108. data.push(0.0);
  60109. data.push(0.0);
  60110. data.push(0.0);
  60111. }
  60112. // direction
  60113. data.push(0.0);
  60114. data.push(0.0);
  60115. data.push(0.0);
  60116. if (!this.isBillboardBased) {
  60117. // initialDirection
  60118. data.push(0.0);
  60119. data.push(0.0);
  60120. data.push(0.0);
  60121. }
  60122. // angle
  60123. data.push(0.0);
  60124. if (!this._angularSpeedGradientsTexture) {
  60125. data.push(0.0);
  60126. }
  60127. if (this._isAnimationSheetEnabled) {
  60128. data.push(0.0);
  60129. }
  60130. }
  60131. // Sprite data
  60132. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  60133. -0.5, 0.5, 0, 1,
  60134. -0.5, -0.5, 0, 0,
  60135. 0.5, -0.5, 1, 0]);
  60136. // Buffers
  60137. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60138. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60139. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  60140. // Update VAO
  60141. this._updateVAO = [];
  60142. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  60143. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  60144. // Render VAO
  60145. this._renderVAO = [];
  60146. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  60147. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  60148. // Links
  60149. this._sourceBuffer = this._buffer0;
  60150. this._targetBuffer = this._buffer1;
  60151. };
  60152. /** @hidden */
  60153. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  60154. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  60155. if (this._isBillboardBased) {
  60156. defines += "\n#define BILLBOARD";
  60157. }
  60158. if (this._colorGradientsTexture) {
  60159. defines += "\n#define COLORGRADIENTS";
  60160. }
  60161. if (this._sizeGradientsTexture) {
  60162. defines += "\n#define SIZEGRADIENTS";
  60163. }
  60164. if (this._angularSpeedGradientsTexture) {
  60165. defines += "\n#define ANGULARSPEEDGRADIENTS";
  60166. }
  60167. if (this._velocityGradientsTexture) {
  60168. defines += "\n#define VELOCITYGRADIENTS";
  60169. }
  60170. if (this.isAnimationSheetEnabled) {
  60171. defines += "\n#define ANIMATESHEET";
  60172. }
  60173. if (this.noiseTexture) {
  60174. defines += "\n#define NOISE";
  60175. }
  60176. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  60177. return;
  60178. }
  60179. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  60180. if (!this._colorGradientsTexture) {
  60181. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  60182. }
  60183. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  60184. if (!this._isBillboardBased) {
  60185. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  60186. }
  60187. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  60188. if (this.isAnimationSheetEnabled) {
  60189. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  60190. }
  60191. this._updateEffectOptions.defines = defines;
  60192. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  60193. };
  60194. /** @hidden */
  60195. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  60196. var defines = "";
  60197. if (this._scene.clipPlane) {
  60198. defines = "\n#define CLIPPLANE";
  60199. }
  60200. if (this._isBillboardBased) {
  60201. defines += "\n#define BILLBOARD";
  60202. switch (this.billboardMode) {
  60203. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  60204. defines += "\n#define BILLBOARDY";
  60205. break;
  60206. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  60207. default:
  60208. break;
  60209. }
  60210. }
  60211. if (this._colorGradientsTexture) {
  60212. defines += "\n#define COLORGRADIENTS";
  60213. }
  60214. if (this.isAnimationSheetEnabled) {
  60215. defines += "\n#define ANIMATESHEET";
  60216. }
  60217. if (this._renderEffect && this._renderEffect.defines === defines) {
  60218. return;
  60219. }
  60220. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  60221. };
  60222. /**
  60223. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60224. * @param preWarm defines if we are in the pre-warmimg phase
  60225. */
  60226. GPUParticleSystem.prototype.animate = function (preWarm) {
  60227. if (preWarm === void 0) { preWarm = false; }
  60228. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60229. this._actualFrame += this._timeDelta;
  60230. if (!this._stopped) {
  60231. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60232. this.stop();
  60233. }
  60234. }
  60235. };
  60236. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  60237. var texture = this[textureName];
  60238. if (!factorGradients || !factorGradients.length || texture) {
  60239. return;
  60240. }
  60241. var data = new Float32Array(this._rawTextureWidth);
  60242. for (var x = 0; x < this._rawTextureWidth; x++) {
  60243. var ratio = x / this._rawTextureWidth;
  60244. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  60245. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60246. });
  60247. }
  60248. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60249. };
  60250. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  60251. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  60252. };
  60253. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  60254. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  60255. };
  60256. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  60257. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  60258. };
  60259. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  60260. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  60261. return;
  60262. }
  60263. var data = new Uint8Array(this._rawTextureWidth * 4);
  60264. var tmpColor = BABYLON.Tmp.Color4[0];
  60265. for (var x = 0; x < this._rawTextureWidth; x++) {
  60266. var ratio = x / this._rawTextureWidth;
  60267. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  60268. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  60269. data[x * 4] = tmpColor.r * 255;
  60270. data[x * 4 + 1] = tmpColor.g * 255;
  60271. data[x * 4 + 2] = tmpColor.b * 255;
  60272. data[x * 4 + 3] = tmpColor.a * 255;
  60273. });
  60274. }
  60275. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60276. };
  60277. /**
  60278. * Renders the particle system in its current state
  60279. * @param preWarm defines if the system should only update the particles but not render them
  60280. * @returns the current number of particles
  60281. */
  60282. GPUParticleSystem.prototype.render = function (preWarm) {
  60283. if (preWarm === void 0) { preWarm = false; }
  60284. if (!this._started) {
  60285. return 0;
  60286. }
  60287. this._createColorGradientTexture();
  60288. this._createSizeGradientTexture();
  60289. this._createAngularSpeedGradientTexture();
  60290. this._createVelocityGradientTexture();
  60291. this._recreateUpdateEffect();
  60292. this._recreateRenderEffect();
  60293. if (!this.isReady()) {
  60294. return 0;
  60295. }
  60296. if (!preWarm) {
  60297. if (!this._preWarmDone && this.preWarmCycles) {
  60298. for (var index = 0; index < this.preWarmCycles; index++) {
  60299. this.animate(true);
  60300. this.render(true);
  60301. }
  60302. this._preWarmDone = true;
  60303. }
  60304. if (this._currentRenderId === this._scene.getRenderId()) {
  60305. return 0;
  60306. }
  60307. this._currentRenderId = this._scene.getRenderId();
  60308. }
  60309. // Get everything ready to render
  60310. this._initialize();
  60311. this._accumulatedCount += this.emitRate * this._timeDelta;
  60312. if (this._accumulatedCount > 1) {
  60313. var intPart = this._accumulatedCount | 0;
  60314. this._accumulatedCount -= intPart;
  60315. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60316. }
  60317. if (!this._currentActiveCount) {
  60318. return 0;
  60319. }
  60320. // Enable update effect
  60321. this._engine.enableEffect(this._updateEffect);
  60322. this._engine.setState(false);
  60323. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60324. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60325. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60326. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60327. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60328. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  60329. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  60330. if (!this._colorGradientsTexture) {
  60331. this._updateEffect.setDirectColor4("color1", this.color1);
  60332. this._updateEffect.setDirectColor4("color2", this.color2);
  60333. }
  60334. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  60335. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  60336. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  60337. this._updateEffect.setVector3("gravity", this.gravity);
  60338. if (this._sizeGradientsTexture) {
  60339. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  60340. }
  60341. if (this._angularSpeedGradientsTexture) {
  60342. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  60343. }
  60344. if (this._velocityGradientsTexture) {
  60345. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  60346. }
  60347. if (this.particleEmitterType) {
  60348. this.particleEmitterType.applyToShader(this._updateEffect);
  60349. }
  60350. if (this._isAnimationSheetEnabled) {
  60351. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  60352. }
  60353. if (this.noiseTexture) {
  60354. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  60355. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  60356. }
  60357. var emitterWM;
  60358. if (this.emitter.position) {
  60359. var emitterMesh = this.emitter;
  60360. emitterWM = emitterMesh.getWorldMatrix();
  60361. }
  60362. else {
  60363. var emitterPosition = this.emitter;
  60364. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60365. }
  60366. this._updateEffect.setMatrix("emitterWM", emitterWM);
  60367. // Bind source VAO
  60368. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  60369. // Update
  60370. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  60371. this._engine.setRasterizerState(false);
  60372. this._engine.beginTransformFeedback(true);
  60373. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  60374. this._engine.endTransformFeedback();
  60375. this._engine.setRasterizerState(true);
  60376. this._engine.bindTransformFeedbackBuffer(null);
  60377. if (!preWarm) {
  60378. // Enable render effect
  60379. this._engine.enableEffect(this._renderEffect);
  60380. var viewMatrix = this._scene.getViewMatrix();
  60381. this._renderEffect.setMatrix("view", viewMatrix);
  60382. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  60383. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  60384. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  60385. if (this._colorGradientsTexture) {
  60386. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  60387. }
  60388. else {
  60389. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  60390. }
  60391. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60392. var baseSize = this.particleTexture.getBaseSize();
  60393. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60394. }
  60395. if (this._isBillboardBased) {
  60396. var camera = this._scene.activeCamera;
  60397. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60398. }
  60399. if (this._scene.clipPlane) {
  60400. var clipPlane = this._scene.clipPlane;
  60401. var invView = viewMatrix.clone();
  60402. invView.invert();
  60403. this._renderEffect.setMatrix("invView", invView);
  60404. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60405. }
  60406. // Draw order
  60407. switch (this.blendMode) {
  60408. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60409. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60410. break;
  60411. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60412. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60413. break;
  60414. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60415. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60416. break;
  60417. }
  60418. if (this.forceDepthWrite) {
  60419. this._engine.setDepthWrite(true);
  60420. }
  60421. // Bind source VAO
  60422. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60423. // Render
  60424. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60425. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60426. }
  60427. // Switch VAOs
  60428. this._targetIndex++;
  60429. if (this._targetIndex === 2) {
  60430. this._targetIndex = 0;
  60431. }
  60432. // Switch buffers
  60433. var tmpBuffer = this._sourceBuffer;
  60434. this._sourceBuffer = this._targetBuffer;
  60435. this._targetBuffer = tmpBuffer;
  60436. return this._currentActiveCount;
  60437. };
  60438. /**
  60439. * Rebuilds the particle system
  60440. */
  60441. GPUParticleSystem.prototype.rebuild = function () {
  60442. this._initialize(true);
  60443. };
  60444. GPUParticleSystem.prototype._releaseBuffers = function () {
  60445. if (this._buffer0) {
  60446. this._buffer0.dispose();
  60447. this._buffer0 = null;
  60448. }
  60449. if (this._buffer1) {
  60450. this._buffer1.dispose();
  60451. this._buffer1 = null;
  60452. }
  60453. if (this._spriteBuffer) {
  60454. this._spriteBuffer.dispose();
  60455. this._spriteBuffer = null;
  60456. }
  60457. };
  60458. GPUParticleSystem.prototype._releaseVAOs = function () {
  60459. if (!this._updateVAO) {
  60460. return;
  60461. }
  60462. for (var index = 0; index < this._updateVAO.length; index++) {
  60463. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60464. }
  60465. this._updateVAO = [];
  60466. for (var index = 0; index < this._renderVAO.length; index++) {
  60467. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60468. }
  60469. this._renderVAO = [];
  60470. };
  60471. /**
  60472. * Disposes the particle system and free the associated resources
  60473. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60474. */
  60475. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60476. if (disposeTexture === void 0) { disposeTexture = true; }
  60477. var index = this._scene.particleSystems.indexOf(this);
  60478. if (index > -1) {
  60479. this._scene.particleSystems.splice(index, 1);
  60480. }
  60481. this._releaseBuffers();
  60482. this._releaseVAOs();
  60483. if (this._colorGradientsTexture) {
  60484. this._colorGradientsTexture.dispose();
  60485. this._colorGradientsTexture = null;
  60486. }
  60487. if (this._sizeGradientsTexture) {
  60488. this._sizeGradientsTexture.dispose();
  60489. this._sizeGradientsTexture = null;
  60490. }
  60491. if (this._angularSpeedGradientsTexture) {
  60492. this._angularSpeedGradientsTexture.dispose();
  60493. this._angularSpeedGradientsTexture = null;
  60494. }
  60495. if (this._velocityGradientsTexture) {
  60496. this._velocityGradientsTexture.dispose();
  60497. this._velocityGradientsTexture = null;
  60498. }
  60499. if (this._randomTexture) {
  60500. this._randomTexture.dispose();
  60501. this._randomTexture = null;
  60502. }
  60503. if (this._randomTexture2) {
  60504. this._randomTexture2.dispose();
  60505. this._randomTexture2 = null;
  60506. }
  60507. if (disposeTexture && this.particleTexture) {
  60508. this.particleTexture.dispose();
  60509. this.particleTexture = null;
  60510. }
  60511. if (disposeTexture && this.noiseTexture) {
  60512. this.noiseTexture.dispose();
  60513. this.noiseTexture = null;
  60514. }
  60515. // Callback
  60516. this.onDisposeObservable.notifyObservers(this);
  60517. this.onDisposeObservable.clear();
  60518. };
  60519. /**
  60520. * Clones the particle system.
  60521. * @param name The name of the cloned object
  60522. * @param newEmitter The new emitter to use
  60523. * @returns the cloned particle system
  60524. */
  60525. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60526. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60527. BABYLON.Tools.DeepCopy(this, result);
  60528. if (newEmitter === undefined) {
  60529. newEmitter = this.emitter;
  60530. }
  60531. result.emitter = newEmitter;
  60532. if (this.particleTexture) {
  60533. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60534. }
  60535. return result;
  60536. };
  60537. /**
  60538. * Serializes the particle system to a JSON object.
  60539. * @returns the JSON object
  60540. */
  60541. GPUParticleSystem.prototype.serialize = function () {
  60542. var serializationObject = {};
  60543. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  60544. serializationObject.activeParticleCount = this.activeParticleCount;
  60545. return serializationObject;
  60546. };
  60547. /**
  60548. * Parses a JSON object to create a GPU particle system.
  60549. * @param parsedParticleSystem The JSON object to parse
  60550. * @param scene The scene to create the particle system in
  60551. * @param rootUrl The root url to use to load external dependencies like texture
  60552. * @returns the parsed GPU particle system
  60553. */
  60554. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  60555. var name = parsedParticleSystem.name;
  60556. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  60557. if (parsedParticleSystem.activeParticleCount) {
  60558. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  60559. }
  60560. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60561. return particleSystem;
  60562. };
  60563. return GPUParticleSystem;
  60564. }());
  60565. BABYLON.GPUParticleSystem = GPUParticleSystem;
  60566. })(BABYLON || (BABYLON = {}));
  60567. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  60568. var BABYLON;
  60569. (function (BABYLON) {
  60570. /**
  60571. * Represents one particle of a solid particle system.
  60572. */
  60573. var SolidParticle = /** @class */ (function () {
  60574. /**
  60575. * Creates a Solid Particle object.
  60576. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  60577. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  60578. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  60579. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  60580. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  60581. * @param shapeId (integer) is the model shape identifier in the SPS.
  60582. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  60583. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  60584. */
  60585. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  60586. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  60587. /**
  60588. * particle global index
  60589. */
  60590. this.idx = 0;
  60591. /**
  60592. * The color of the particle
  60593. */
  60594. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60595. /**
  60596. * The world space position of the particle.
  60597. */
  60598. this.position = BABYLON.Vector3.Zero();
  60599. /**
  60600. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  60601. */
  60602. this.rotation = BABYLON.Vector3.Zero();
  60603. /**
  60604. * The scaling of the particle.
  60605. */
  60606. this.scaling = BABYLON.Vector3.One();
  60607. /**
  60608. * The uvs of the particle.
  60609. */
  60610. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  60611. /**
  60612. * The current speed of the particle.
  60613. */
  60614. this.velocity = BABYLON.Vector3.Zero();
  60615. /**
  60616. * The pivot point in the particle local space.
  60617. */
  60618. this.pivot = BABYLON.Vector3.Zero();
  60619. /**
  60620. * Must the particle be translated from its pivot point in its local space ?
  60621. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  60622. * Default : false
  60623. */
  60624. this.translateFromPivot = false;
  60625. /**
  60626. * Is the particle active or not ?
  60627. */
  60628. this.alive = true;
  60629. /**
  60630. * Is the particle visible or not ?
  60631. */
  60632. this.isVisible = true;
  60633. /**
  60634. * Index of this particle in the global "positions" array (Internal use)
  60635. */
  60636. this._pos = 0;
  60637. /**
  60638. * Index of this particle in the global "indices" array (Internal use)
  60639. */
  60640. this._ind = 0;
  60641. /**
  60642. * ModelShape id of this particle
  60643. */
  60644. this.shapeId = 0;
  60645. /**
  60646. * Index of the particle in its shape id (Internal use)
  60647. */
  60648. this.idxInShape = 0;
  60649. /**
  60650. * Still set as invisible in order to skip useless computations (Internal use)
  60651. */
  60652. this._stillInvisible = false;
  60653. /**
  60654. * Last computed particle rotation matrix
  60655. */
  60656. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  60657. /**
  60658. * Parent particle Id, if any.
  60659. * Default null.
  60660. */
  60661. this.parentId = null;
  60662. /**
  60663. * Internal global position in the SPS.
  60664. */
  60665. this._globalPosition = BABYLON.Vector3.Zero();
  60666. this.idx = particleIndex;
  60667. this._pos = positionIndex;
  60668. this._ind = indiceIndex;
  60669. this._model = model;
  60670. this.shapeId = shapeId;
  60671. this.idxInShape = idxInShape;
  60672. this._sps = sps;
  60673. if (modelBoundingInfo) {
  60674. this._modelBoundingInfo = modelBoundingInfo;
  60675. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  60676. }
  60677. }
  60678. Object.defineProperty(SolidParticle.prototype, "scale", {
  60679. /**
  60680. * Legacy support, changed scale to scaling
  60681. */
  60682. get: function () {
  60683. return this.scaling;
  60684. },
  60685. /**
  60686. * Legacy support, changed scale to scaling
  60687. */
  60688. set: function (scale) {
  60689. this.scaling = scale;
  60690. },
  60691. enumerable: true,
  60692. configurable: true
  60693. });
  60694. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  60695. /**
  60696. * Legacy support, changed quaternion to rotationQuaternion
  60697. */
  60698. get: function () {
  60699. return this.rotationQuaternion;
  60700. },
  60701. /**
  60702. * Legacy support, changed quaternion to rotationQuaternion
  60703. */
  60704. set: function (q) {
  60705. this.rotationQuaternion = q;
  60706. },
  60707. enumerable: true,
  60708. configurable: true
  60709. });
  60710. /**
  60711. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  60712. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  60713. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  60714. * @returns true if it intersects
  60715. */
  60716. SolidParticle.prototype.intersectsMesh = function (target) {
  60717. if (!this._boundingInfo || !target._boundingInfo) {
  60718. return false;
  60719. }
  60720. if (this._sps._bSphereOnly) {
  60721. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  60722. }
  60723. return this._boundingInfo.intersects(target._boundingInfo, false);
  60724. };
  60725. return SolidParticle;
  60726. }());
  60727. BABYLON.SolidParticle = SolidParticle;
  60728. /**
  60729. * Represents the shape of the model used by one particle of a solid particle system.
  60730. * SPS internal tool, don't use it manually.
  60731. */
  60732. var ModelShape = /** @class */ (function () {
  60733. /**
  60734. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  60735. * SPS internal tool, don't use it manually.
  60736. * @hidden
  60737. */
  60738. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  60739. /**
  60740. * length of the shape in the model indices array (internal use)
  60741. */
  60742. this._indicesLength = 0;
  60743. this.shapeID = id;
  60744. this._shape = shape;
  60745. this._indicesLength = indicesLength;
  60746. this._shapeUV = shapeUV;
  60747. this._positionFunction = posFunction;
  60748. this._vertexFunction = vtxFunction;
  60749. }
  60750. return ModelShape;
  60751. }());
  60752. BABYLON.ModelShape = ModelShape;
  60753. /**
  60754. * Represents a Depth Sorted Particle in the solid particle system.
  60755. */
  60756. var DepthSortedParticle = /** @class */ (function () {
  60757. function DepthSortedParticle() {
  60758. /**
  60759. * Index of the particle in the "indices" array
  60760. */
  60761. this.ind = 0;
  60762. /**
  60763. * Length of the particle shape in the "indices" array
  60764. */
  60765. this.indicesLength = 0;
  60766. /**
  60767. * Squared distance from the particle to the camera
  60768. */
  60769. this.sqDistance = 0.0;
  60770. }
  60771. return DepthSortedParticle;
  60772. }());
  60773. BABYLON.DepthSortedParticle = DepthSortedParticle;
  60774. })(BABYLON || (BABYLON = {}));
  60775. //# sourceMappingURL=babylon.solidParticle.js.map
  60776. var BABYLON;
  60777. (function (BABYLON) {
  60778. /**
  60779. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  60780. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  60781. * The SPS is also a particle system. It provides some methods to manage the particles.
  60782. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  60783. *
  60784. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  60785. */
  60786. var SolidParticleSystem = /** @class */ (function () {
  60787. /**
  60788. * Creates a SPS (Solid Particle System) object.
  60789. * @param name (String) is the SPS name, this will be the underlying mesh name.
  60790. * @param scene (Scene) is the scene in which the SPS is added.
  60791. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  60792. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  60793. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  60794. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  60795. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  60796. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  60797. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  60798. */
  60799. function SolidParticleSystem(name, scene, options) {
  60800. /**
  60801. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  60802. * Example : var p = SPS.particles[i];
  60803. */
  60804. this.particles = new Array();
  60805. /**
  60806. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  60807. */
  60808. this.nbParticles = 0;
  60809. /**
  60810. * If the particles must ever face the camera (default false). Useful for planar particles.
  60811. */
  60812. this.billboard = false;
  60813. /**
  60814. * Recompute normals when adding a shape
  60815. */
  60816. this.recomputeNormals = true;
  60817. /**
  60818. * This a counter ofr your own usage. It's not set by any SPS functions.
  60819. */
  60820. this.counter = 0;
  60821. /**
  60822. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  60823. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  60824. */
  60825. this.vars = {};
  60826. /**
  60827. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  60828. */
  60829. this._bSphereOnly = false;
  60830. /**
  60831. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  60832. */
  60833. this._bSphereRadiusFactor = 1.0;
  60834. this._positions = new Array();
  60835. this._indices = new Array();
  60836. this._normals = new Array();
  60837. this._colors = new Array();
  60838. this._uvs = new Array();
  60839. this._index = 0; // indices index
  60840. this._updatable = true;
  60841. this._pickable = false;
  60842. this._isVisibilityBoxLocked = false;
  60843. this._alwaysVisible = false;
  60844. this._depthSort = false;
  60845. this._shapeCounter = 0;
  60846. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  60847. this._color = new BABYLON.Color4(0, 0, 0, 0);
  60848. this._computeParticleColor = true;
  60849. this._computeParticleTexture = true;
  60850. this._computeParticleRotation = true;
  60851. this._computeParticleVertex = false;
  60852. this._computeBoundingBox = false;
  60853. this._depthSortParticles = true;
  60854. this._cam_axisZ = BABYLON.Vector3.Zero();
  60855. this._cam_axisY = BABYLON.Vector3.Zero();
  60856. this._cam_axisX = BABYLON.Vector3.Zero();
  60857. this._axisZ = BABYLON.Axis.Z;
  60858. this._camDir = BABYLON.Vector3.Zero();
  60859. this._camInvertedPosition = BABYLON.Vector3.Zero();
  60860. this._rotMatrix = new BABYLON.Matrix();
  60861. this._invertMatrix = new BABYLON.Matrix();
  60862. this._rotated = BABYLON.Vector3.Zero();
  60863. this._quaternion = new BABYLON.Quaternion();
  60864. this._vertex = BABYLON.Vector3.Zero();
  60865. this._normal = BABYLON.Vector3.Zero();
  60866. this._yaw = 0.0;
  60867. this._pitch = 0.0;
  60868. this._roll = 0.0;
  60869. this._halfroll = 0.0;
  60870. this._halfpitch = 0.0;
  60871. this._halfyaw = 0.0;
  60872. this._sinRoll = 0.0;
  60873. this._cosRoll = 0.0;
  60874. this._sinPitch = 0.0;
  60875. this._cosPitch = 0.0;
  60876. this._sinYaw = 0.0;
  60877. this._cosYaw = 0.0;
  60878. this._mustUnrotateFixedNormals = false;
  60879. this._minimum = BABYLON.Vector3.Zero();
  60880. this._maximum = BABYLON.Vector3.Zero();
  60881. this._minBbox = BABYLON.Vector3.Zero();
  60882. this._maxBbox = BABYLON.Vector3.Zero();
  60883. this._particlesIntersect = false;
  60884. this._depthSortFunction = function (p1, p2) {
  60885. return (p2.sqDistance - p1.sqDistance);
  60886. };
  60887. this._needs32Bits = false;
  60888. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  60889. this._scaledPivot = BABYLON.Vector3.Zero();
  60890. this._particleHasParent = false;
  60891. this.name = name;
  60892. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60893. this._camera = scene.activeCamera;
  60894. this._pickable = options ? options.isPickable : false;
  60895. this._depthSort = options ? options.enableDepthSort : false;
  60896. this._particlesIntersect = options ? options.particleIntersection : false;
  60897. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  60898. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  60899. if (options && options.updatable !== undefined) {
  60900. this._updatable = options.updatable;
  60901. }
  60902. else {
  60903. this._updatable = true;
  60904. }
  60905. if (this._pickable) {
  60906. this.pickedParticles = [];
  60907. }
  60908. if (this._depthSort) {
  60909. this.depthSortedParticles = [];
  60910. }
  60911. }
  60912. /**
  60913. * Builds the SPS underlying mesh. Returns a standard Mesh.
  60914. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  60915. * @returns the created mesh
  60916. */
  60917. SolidParticleSystem.prototype.buildMesh = function () {
  60918. if (this.nbParticles === 0) {
  60919. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  60920. this.addShape(triangle, 1);
  60921. triangle.dispose();
  60922. }
  60923. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  60924. this._positions32 = new Float32Array(this._positions);
  60925. this._uvs32 = new Float32Array(this._uvs);
  60926. this._colors32 = new Float32Array(this._colors);
  60927. if (this.recomputeNormals) {
  60928. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  60929. }
  60930. this._normals32 = new Float32Array(this._normals);
  60931. this._fixedNormal32 = new Float32Array(this._normals);
  60932. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  60933. this._unrotateFixedNormals();
  60934. }
  60935. var vertexData = new BABYLON.VertexData();
  60936. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  60937. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  60938. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  60939. if (this._uvs32.length > 0) {
  60940. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  60941. }
  60942. if (this._colors32.length > 0) {
  60943. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  60944. }
  60945. var mesh = new BABYLON.Mesh(this.name, this._scene);
  60946. vertexData.applyToMesh(mesh, this._updatable);
  60947. this.mesh = mesh;
  60948. this.mesh.isPickable = this._pickable;
  60949. // free memory
  60950. if (!this._depthSort) {
  60951. this._indices = null;
  60952. }
  60953. this._positions = null;
  60954. this._normals = null;
  60955. this._uvs = null;
  60956. this._colors = null;
  60957. if (!this._updatable) {
  60958. this.particles.length = 0;
  60959. }
  60960. return mesh;
  60961. };
  60962. /**
  60963. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  60964. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  60965. * Thus the particles generated from `digest()` have their property `position` set yet.
  60966. * @param mesh ( Mesh ) is the mesh to be digested
  60967. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  60968. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  60969. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  60970. * @returns the current SPS
  60971. */
  60972. SolidParticleSystem.prototype.digest = function (mesh, options) {
  60973. var size = (options && options.facetNb) || 1;
  60974. var number = (options && options.number) || 0;
  60975. var delta = (options && options.delta) || 0;
  60976. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60977. var meshInd = mesh.getIndices();
  60978. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60979. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60980. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60981. var f = 0; // facet counter
  60982. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  60983. // compute size from number
  60984. if (number) {
  60985. number = (number > totalFacets) ? totalFacets : number;
  60986. size = Math.round(totalFacets / number);
  60987. delta = 0;
  60988. }
  60989. else {
  60990. size = (size > totalFacets) ? totalFacets : size;
  60991. }
  60992. var facetPos = []; // submesh positions
  60993. var facetInd = []; // submesh indices
  60994. var facetUV = []; // submesh UV
  60995. var facetCol = []; // submesh colors
  60996. var barycenter = BABYLON.Vector3.Zero();
  60997. var sizeO = size;
  60998. while (f < totalFacets) {
  60999. size = sizeO + Math.floor((1 + delta) * Math.random());
  61000. if (f > totalFacets - size) {
  61001. size = totalFacets - f;
  61002. }
  61003. // reset temp arrays
  61004. facetPos.length = 0;
  61005. facetInd.length = 0;
  61006. facetUV.length = 0;
  61007. facetCol.length = 0;
  61008. // iterate over "size" facets
  61009. var fi = 0;
  61010. for (var j = f * 3; j < (f + size) * 3; j++) {
  61011. facetInd.push(fi);
  61012. var i = meshInd[j];
  61013. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61014. if (meshUV) {
  61015. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61016. }
  61017. if (meshCol) {
  61018. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61019. }
  61020. fi++;
  61021. }
  61022. // create a model shape for each single particle
  61023. var idx = this.nbParticles;
  61024. var shape = this._posToShape(facetPos);
  61025. var shapeUV = this._uvsToShapeUV(facetUV);
  61026. // compute the barycenter of the shape
  61027. var v;
  61028. for (v = 0; v < shape.length; v++) {
  61029. barycenter.addInPlace(shape[v]);
  61030. }
  61031. barycenter.scaleInPlace(1 / shape.length);
  61032. // shift the shape from its barycenter to the origin
  61033. for (v = 0; v < shape.length; v++) {
  61034. shape[v].subtractInPlace(barycenter);
  61035. }
  61036. var bInfo;
  61037. if (this._particlesIntersect) {
  61038. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61039. }
  61040. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61041. // add the particle in the SPS
  61042. var currentPos = this._positions.length;
  61043. var currentInd = this._indices.length;
  61044. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61045. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61046. // initialize the particle position
  61047. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61048. this._index += shape.length;
  61049. idx++;
  61050. this.nbParticles++;
  61051. this._shapeCounter++;
  61052. f += size;
  61053. }
  61054. return this;
  61055. };
  61056. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61057. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61058. var index = 0;
  61059. var idx = 0;
  61060. for (var p = 0; p < this.particles.length; p++) {
  61061. this._particle = this.particles[p];
  61062. this._shape = this._particle._model._shape;
  61063. if (this._particle.rotationQuaternion) {
  61064. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61065. }
  61066. else {
  61067. this._yaw = this._particle.rotation.y;
  61068. this._pitch = this._particle.rotation.x;
  61069. this._roll = this._particle.rotation.z;
  61070. this._quaternionRotationYPR();
  61071. }
  61072. this._quaternionToRotationMatrix();
  61073. this._rotMatrix.invertToRef(this._invertMatrix);
  61074. for (var pt = 0; pt < this._shape.length; pt++) {
  61075. idx = index + pt * 3;
  61076. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  61077. this._fixedNormal32[idx] = this._normal.x;
  61078. this._fixedNormal32[idx + 1] = this._normal.y;
  61079. this._fixedNormal32[idx + 2] = this._normal.z;
  61080. }
  61081. index = idx + 3;
  61082. }
  61083. };
  61084. //reset copy
  61085. SolidParticleSystem.prototype._resetCopy = function () {
  61086. this._copy.position.x = 0;
  61087. this._copy.position.y = 0;
  61088. this._copy.position.z = 0;
  61089. this._copy.rotation.x = 0;
  61090. this._copy.rotation.y = 0;
  61091. this._copy.rotation.z = 0;
  61092. this._copy.rotationQuaternion = null;
  61093. this._copy.scaling.x = 1.0;
  61094. this._copy.scaling.y = 1.0;
  61095. this._copy.scaling.z = 1.0;
  61096. this._copy.uvs.x = 0;
  61097. this._copy.uvs.y = 0;
  61098. this._copy.uvs.z = 1.0;
  61099. this._copy.uvs.w = 1.0;
  61100. this._copy.color = null;
  61101. this._copy.translateFromPivot = false;
  61102. };
  61103. // _meshBuilder : inserts the shape model in the global SPS mesh
  61104. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  61105. var i;
  61106. var u = 0;
  61107. var c = 0;
  61108. var n = 0;
  61109. this._resetCopy();
  61110. if (options && options.positionFunction) { // call to custom positionFunction
  61111. options.positionFunction(this._copy, idx, idxInShape);
  61112. this._mustUnrotateFixedNormals = true;
  61113. }
  61114. if (this._copy.rotationQuaternion) {
  61115. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61116. }
  61117. else {
  61118. this._yaw = this._copy.rotation.y;
  61119. this._pitch = this._copy.rotation.x;
  61120. this._roll = this._copy.rotation.z;
  61121. this._quaternionRotationYPR();
  61122. }
  61123. this._quaternionToRotationMatrix();
  61124. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  61125. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  61126. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  61127. if (this._copy.translateFromPivot) {
  61128. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61129. }
  61130. else {
  61131. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61132. }
  61133. for (i = 0; i < shape.length; i++) {
  61134. this._vertex.x = shape[i].x;
  61135. this._vertex.y = shape[i].y;
  61136. this._vertex.z = shape[i].z;
  61137. if (options && options.vertexFunction) {
  61138. options.vertexFunction(this._copy, this._vertex, i);
  61139. }
  61140. this._vertex.x *= this._copy.scaling.x;
  61141. this._vertex.y *= this._copy.scaling.y;
  61142. this._vertex.z *= this._copy.scaling.z;
  61143. this._vertex.x -= this._scaledPivot.x;
  61144. this._vertex.y -= this._scaledPivot.y;
  61145. this._vertex.z -= this._scaledPivot.z;
  61146. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61147. this._rotated.addInPlace(this._pivotBackTranslation);
  61148. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  61149. if (meshUV) {
  61150. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  61151. u += 2;
  61152. }
  61153. if (this._copy.color) {
  61154. this._color = this._copy.color;
  61155. }
  61156. else if (meshCol && meshCol[c] !== undefined) {
  61157. this._color.r = meshCol[c];
  61158. this._color.g = meshCol[c + 1];
  61159. this._color.b = meshCol[c + 2];
  61160. this._color.a = meshCol[c + 3];
  61161. }
  61162. else {
  61163. this._color.r = 1.0;
  61164. this._color.g = 1.0;
  61165. this._color.b = 1.0;
  61166. this._color.a = 1.0;
  61167. }
  61168. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  61169. c += 4;
  61170. if (!this.recomputeNormals && meshNor) {
  61171. this._normal.x = meshNor[n];
  61172. this._normal.y = meshNor[n + 1];
  61173. this._normal.z = meshNor[n + 2];
  61174. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  61175. normals.push(this._normal.x, this._normal.y, this._normal.z);
  61176. n += 3;
  61177. }
  61178. }
  61179. for (i = 0; i < meshInd.length; i++) {
  61180. var current_ind = p + meshInd[i];
  61181. indices.push(current_ind);
  61182. if (current_ind > 65535) {
  61183. this._needs32Bits = true;
  61184. }
  61185. }
  61186. if (this._pickable) {
  61187. var nbfaces = meshInd.length / 3;
  61188. for (i = 0; i < nbfaces; i++) {
  61189. this.pickedParticles.push({ idx: idx, faceId: i });
  61190. }
  61191. }
  61192. if (this._depthSort) {
  61193. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  61194. }
  61195. return this._copy;
  61196. };
  61197. // returns a shape array from positions array
  61198. SolidParticleSystem.prototype._posToShape = function (positions) {
  61199. var shape = [];
  61200. for (var i = 0; i < positions.length; i += 3) {
  61201. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  61202. }
  61203. return shape;
  61204. };
  61205. // returns a shapeUV array from a Vector4 uvs
  61206. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  61207. var shapeUV = [];
  61208. if (uvs) {
  61209. for (var i = 0; i < uvs.length; i++)
  61210. shapeUV.push(uvs[i]);
  61211. }
  61212. return shapeUV;
  61213. };
  61214. // adds a new particle object in the particles array
  61215. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  61216. if (bInfo === void 0) { bInfo = null; }
  61217. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  61218. this.particles.push(sp);
  61219. return sp;
  61220. };
  61221. /**
  61222. * Adds some particles to the SPS from the model shape. Returns the shape id.
  61223. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  61224. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  61225. * @param nb (positive integer) the number of particles to be created from this model
  61226. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  61227. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  61228. * @returns the number of shapes in the system
  61229. */
  61230. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  61231. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61232. var meshInd = mesh.getIndices();
  61233. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61234. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61235. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61236. var bbInfo;
  61237. if (this._particlesIntersect) {
  61238. bbInfo = mesh.getBoundingInfo();
  61239. }
  61240. var shape = this._posToShape(meshPos);
  61241. var shapeUV = this._uvsToShapeUV(meshUV);
  61242. var posfunc = options ? options.positionFunction : null;
  61243. var vtxfunc = options ? options.vertexFunction : null;
  61244. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  61245. // particles
  61246. var sp;
  61247. var currentCopy;
  61248. var idx = this.nbParticles;
  61249. for (var i = 0; i < nb; i++) {
  61250. var currentPos = this._positions.length;
  61251. var currentInd = this._indices.length;
  61252. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  61253. if (this._updatable) {
  61254. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  61255. sp.position.copyFrom(currentCopy.position);
  61256. sp.rotation.copyFrom(currentCopy.rotation);
  61257. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  61258. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  61259. }
  61260. if (currentCopy.color && sp.color) {
  61261. sp.color.copyFrom(currentCopy.color);
  61262. }
  61263. sp.scaling.copyFrom(currentCopy.scaling);
  61264. sp.uvs.copyFrom(currentCopy.uvs);
  61265. }
  61266. this._index += shape.length;
  61267. idx++;
  61268. }
  61269. this.nbParticles += nb;
  61270. this._shapeCounter++;
  61271. return this._shapeCounter - 1;
  61272. };
  61273. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  61274. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  61275. this._resetCopy();
  61276. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  61277. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  61278. }
  61279. if (this._copy.rotationQuaternion) {
  61280. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61281. }
  61282. else {
  61283. this._yaw = this._copy.rotation.y;
  61284. this._pitch = this._copy.rotation.x;
  61285. this._roll = this._copy.rotation.z;
  61286. this._quaternionRotationYPR();
  61287. }
  61288. this._quaternionToRotationMatrix();
  61289. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61290. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61291. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61292. if (this._copy.translateFromPivot) {
  61293. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61294. }
  61295. else {
  61296. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61297. }
  61298. this._shape = particle._model._shape;
  61299. for (var pt = 0; pt < this._shape.length; pt++) {
  61300. this._vertex.x = this._shape[pt].x;
  61301. this._vertex.y = this._shape[pt].y;
  61302. this._vertex.z = this._shape[pt].z;
  61303. if (particle._model._vertexFunction) {
  61304. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  61305. }
  61306. this._vertex.x *= this._copy.scaling.x;
  61307. this._vertex.y *= this._copy.scaling.y;
  61308. this._vertex.z *= this._copy.scaling.z;
  61309. this._vertex.x -= this._scaledPivot.x;
  61310. this._vertex.y -= this._scaledPivot.y;
  61311. this._vertex.z -= this._scaledPivot.z;
  61312. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61313. this._rotated.addInPlace(this._pivotBackTranslation);
  61314. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  61315. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  61316. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  61317. }
  61318. particle.position.x = 0.0;
  61319. particle.position.y = 0.0;
  61320. particle.position.z = 0.0;
  61321. particle.rotation.x = 0.0;
  61322. particle.rotation.y = 0.0;
  61323. particle.rotation.z = 0.0;
  61324. particle.rotationQuaternion = null;
  61325. particle.scaling.x = 1.0;
  61326. particle.scaling.y = 1.0;
  61327. particle.scaling.z = 1.0;
  61328. particle.uvs.x = 0.0;
  61329. particle.uvs.y = 0.0;
  61330. particle.uvs.z = 1.0;
  61331. particle.uvs.w = 1.0;
  61332. particle.pivot.x = 0.0;
  61333. particle.pivot.y = 0.0;
  61334. particle.pivot.z = 0.0;
  61335. particle.translateFromPivot = false;
  61336. particle.parentId = null;
  61337. };
  61338. /**
  61339. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  61340. * @returns the SPS.
  61341. */
  61342. SolidParticleSystem.prototype.rebuildMesh = function () {
  61343. for (var p = 0; p < this.particles.length; p++) {
  61344. this._rebuildParticle(this.particles[p]);
  61345. }
  61346. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61347. return this;
  61348. };
  61349. /**
  61350. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  61351. * This method calls `updateParticle()` for each particle of the SPS.
  61352. * For an animated SPS, it is usually called within the render loop.
  61353. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  61354. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  61355. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  61356. * @returns the SPS.
  61357. */
  61358. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  61359. if (start === void 0) { start = 0; }
  61360. if (end === void 0) { end = this.nbParticles - 1; }
  61361. if (update === void 0) { update = true; }
  61362. if (!this._updatable) {
  61363. return this;
  61364. }
  61365. // custom beforeUpdate
  61366. this.beforeUpdateParticles(start, end, update);
  61367. this._cam_axisX.x = 1.0;
  61368. this._cam_axisX.y = 0.0;
  61369. this._cam_axisX.z = 0.0;
  61370. this._cam_axisY.x = 0.0;
  61371. this._cam_axisY.y = 1.0;
  61372. this._cam_axisY.z = 0.0;
  61373. this._cam_axisZ.x = 0.0;
  61374. this._cam_axisZ.y = 0.0;
  61375. this._cam_axisZ.z = 1.0;
  61376. // cases when the World Matrix is to be computed first
  61377. if (this.billboard || this._depthSort) {
  61378. this.mesh.computeWorldMatrix(true);
  61379. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  61380. }
  61381. // if the particles will always face the camera
  61382. if (this.billboard) {
  61383. // compute the camera position and un-rotate it by the current mesh rotation
  61384. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  61385. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  61386. this._cam_axisZ.normalize();
  61387. // same for camera up vector extracted from the cam view matrix
  61388. var view = this._camera.getViewMatrix(true);
  61389. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  61390. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  61391. this._cam_axisY.normalize();
  61392. this._cam_axisX.normalize();
  61393. }
  61394. // if depthSort, compute the camera global position in the mesh local system
  61395. if (this._depthSort) {
  61396. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  61397. }
  61398. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61399. var idx = 0; // current position index in the global array positions32
  61400. var index = 0; // position start index in the global array positions32 of the current particle
  61401. var colidx = 0; // current color index in the global array colors32
  61402. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61403. var uvidx = 0; // current uv index in the global array uvs32
  61404. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61405. var pt = 0; // current index in the particle model shape
  61406. if (this.mesh.isFacetDataEnabled) {
  61407. this._computeBoundingBox = true;
  61408. }
  61409. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61410. if (this._computeBoundingBox) {
  61411. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61412. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61413. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61414. }
  61415. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61416. if (this.mesh._boundingInfo) {
  61417. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61418. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61419. }
  61420. }
  61421. }
  61422. // particle loop
  61423. index = this.particles[start]._pos;
  61424. var vpos = (index / 3) | 0;
  61425. colorIndex = vpos * 4;
  61426. uvIndex = vpos * 2;
  61427. for (var p = start; p <= end; p++) {
  61428. this._particle = this.particles[p];
  61429. this._shape = this._particle._model._shape;
  61430. this._shapeUV = this._particle._model._shapeUV;
  61431. // call to custom user function to update the particle properties
  61432. this.updateParticle(this._particle);
  61433. // camera-particle distance for depth sorting
  61434. if (this._depthSort && this._depthSortParticles) {
  61435. var dsp = this.depthSortedParticles[p];
  61436. dsp.ind = this._particle._ind;
  61437. dsp.indicesLength = this._particle._model._indicesLength;
  61438. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61439. }
  61440. // skip the computations for inactive or already invisible particles
  61441. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61442. // increment indexes for the next particle
  61443. pt = this._shape.length;
  61444. index += pt * 3;
  61445. colorIndex += pt * 4;
  61446. uvIndex += pt * 2;
  61447. continue;
  61448. }
  61449. if (this._particle.isVisible) {
  61450. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61451. this._particleHasParent = (this._particle.parentId !== null);
  61452. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61453. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61454. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61455. // particle rotation matrix
  61456. if (this.billboard) {
  61457. this._particle.rotation.x = 0.0;
  61458. this._particle.rotation.y = 0.0;
  61459. }
  61460. if (this._computeParticleRotation || this.billboard) {
  61461. if (this._particle.rotationQuaternion) {
  61462. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61463. }
  61464. else {
  61465. this._yaw = this._particle.rotation.y;
  61466. this._pitch = this._particle.rotation.x;
  61467. this._roll = this._particle.rotation.z;
  61468. this._quaternionRotationYPR();
  61469. }
  61470. this._quaternionToRotationMatrix();
  61471. }
  61472. if (this._particleHasParent) {
  61473. this._parent = this.particles[this._particle.parentId];
  61474. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  61475. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  61476. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  61477. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61478. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61479. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61480. if (this._computeParticleRotation || this.billboard) {
  61481. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  61482. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  61483. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  61484. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  61485. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  61486. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  61487. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  61488. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  61489. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  61490. }
  61491. }
  61492. else {
  61493. this._particle._globalPosition.x = this._particle.position.x;
  61494. this._particle._globalPosition.y = this._particle.position.y;
  61495. this._particle._globalPosition.z = this._particle.position.z;
  61496. if (this._computeParticleRotation || this.billboard) {
  61497. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61498. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61499. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61500. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61501. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61502. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61503. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61504. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61505. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61506. }
  61507. }
  61508. if (this._particle.translateFromPivot) {
  61509. this._pivotBackTranslation.x = 0.0;
  61510. this._pivotBackTranslation.y = 0.0;
  61511. this._pivotBackTranslation.z = 0.0;
  61512. }
  61513. else {
  61514. this._pivotBackTranslation.x = this._scaledPivot.x;
  61515. this._pivotBackTranslation.y = this._scaledPivot.y;
  61516. this._pivotBackTranslation.z = this._scaledPivot.z;
  61517. }
  61518. // particle vertex loop
  61519. for (pt = 0; pt < this._shape.length; pt++) {
  61520. idx = index + pt * 3;
  61521. colidx = colorIndex + pt * 4;
  61522. uvidx = uvIndex + pt * 2;
  61523. this._vertex.x = this._shape[pt].x;
  61524. this._vertex.y = this._shape[pt].y;
  61525. this._vertex.z = this._shape[pt].z;
  61526. if (this._computeParticleVertex) {
  61527. this.updateParticleVertex(this._particle, this._vertex, pt);
  61528. }
  61529. // positions
  61530. this._vertex.x *= this._particle.scaling.x;
  61531. this._vertex.y *= this._particle.scaling.y;
  61532. this._vertex.z *= this._particle.scaling.z;
  61533. this._vertex.x -= this._scaledPivot.x;
  61534. this._vertex.y -= this._scaledPivot.y;
  61535. this._vertex.z -= this._scaledPivot.z;
  61536. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61537. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61538. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61539. this._rotated.x += this._pivotBackTranslation.x;
  61540. this._rotated.y += this._pivotBackTranslation.y;
  61541. this._rotated.z += this._pivotBackTranslation.z;
  61542. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61543. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  61544. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  61545. if (this._computeBoundingBox) {
  61546. if (this._positions32[idx] < this._minimum.x) {
  61547. this._minimum.x = this._positions32[idx];
  61548. }
  61549. if (this._positions32[idx] > this._maximum.x) {
  61550. this._maximum.x = this._positions32[idx];
  61551. }
  61552. if (this._positions32[idx + 1] < this._minimum.y) {
  61553. this._minimum.y = this._positions32[idx + 1];
  61554. }
  61555. if (this._positions32[idx + 1] > this._maximum.y) {
  61556. this._maximum.y = this._positions32[idx + 1];
  61557. }
  61558. if (this._positions32[idx + 2] < this._minimum.z) {
  61559. this._minimum.z = this._positions32[idx + 2];
  61560. }
  61561. if (this._positions32[idx + 2] > this._maximum.z) {
  61562. this._maximum.z = this._positions32[idx + 2];
  61563. }
  61564. }
  61565. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  61566. if (!this._computeParticleVertex) {
  61567. this._normal.x = this._fixedNormal32[idx];
  61568. this._normal.y = this._fixedNormal32[idx + 1];
  61569. this._normal.z = this._fixedNormal32[idx + 2];
  61570. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  61571. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  61572. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  61573. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61574. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  61575. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  61576. }
  61577. if (this._computeParticleColor && this._particle.color) {
  61578. this._colors32[colidx] = this._particle.color.r;
  61579. this._colors32[colidx + 1] = this._particle.color.g;
  61580. this._colors32[colidx + 2] = this._particle.color.b;
  61581. this._colors32[colidx + 3] = this._particle.color.a;
  61582. }
  61583. if (this._computeParticleTexture) {
  61584. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61585. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61586. }
  61587. }
  61588. }
  61589. // particle just set invisible : scaled to zero and positioned at the origin
  61590. else {
  61591. this._particle._stillInvisible = true; // mark the particle as invisible
  61592. for (pt = 0; pt < this._shape.length; pt++) {
  61593. idx = index + pt * 3;
  61594. colidx = colorIndex + pt * 4;
  61595. uvidx = uvIndex + pt * 2;
  61596. this._positions32[idx] = 0.0;
  61597. this._positions32[idx + 1] = 0.0;
  61598. this._positions32[idx + 2] = 0.0;
  61599. this._normals32[idx] = 0.0;
  61600. this._normals32[idx + 1] = 0.0;
  61601. this._normals32[idx + 2] = 0.0;
  61602. if (this._computeParticleColor && this._particle.color) {
  61603. this._colors32[colidx] = this._particle.color.r;
  61604. this._colors32[colidx + 1] = this._particle.color.g;
  61605. this._colors32[colidx + 2] = this._particle.color.b;
  61606. this._colors32[colidx + 3] = this._particle.color.a;
  61607. }
  61608. if (this._computeParticleTexture) {
  61609. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61610. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61611. }
  61612. }
  61613. }
  61614. // if the particle intersections must be computed : update the bbInfo
  61615. if (this._particlesIntersect) {
  61616. var bInfo = this._particle._boundingInfo;
  61617. var bBox = bInfo.boundingBox;
  61618. var bSphere = bInfo.boundingSphere;
  61619. if (!this._bSphereOnly) {
  61620. // place, scale and rotate the particle bbox within the SPS local system, then update it
  61621. for (var b = 0; b < bBox.vectors.length; b++) {
  61622. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  61623. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  61624. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  61625. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61626. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61627. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61628. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61629. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  61630. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  61631. }
  61632. bBox._update(this.mesh._worldMatrix);
  61633. }
  61634. // place and scale the particle bouding sphere in the SPS local system, then update it
  61635. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  61636. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  61637. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  61638. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  61639. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  61640. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  61641. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  61642. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  61643. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  61644. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  61645. bSphere._update(this.mesh._worldMatrix);
  61646. }
  61647. // increment indexes for the next particle
  61648. index = idx + 3;
  61649. colorIndex = colidx + 4;
  61650. uvIndex = uvidx + 2;
  61651. }
  61652. // if the VBO must be updated
  61653. if (update) {
  61654. if (this._computeParticleColor) {
  61655. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  61656. }
  61657. if (this._computeParticleTexture) {
  61658. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  61659. }
  61660. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61661. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  61662. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  61663. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  61664. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  61665. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  61666. for (var i = 0; i < this._normals32.length; i++) {
  61667. this._fixedNormal32[i] = this._normals32[i];
  61668. }
  61669. }
  61670. if (!this.mesh.areNormalsFrozen) {
  61671. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  61672. }
  61673. }
  61674. if (this._depthSort && this._depthSortParticles) {
  61675. this.depthSortedParticles.sort(this._depthSortFunction);
  61676. var dspl = this.depthSortedParticles.length;
  61677. var sorted = 0;
  61678. var lind = 0;
  61679. var sind = 0;
  61680. var sid = 0;
  61681. for (sorted = 0; sorted < dspl; sorted++) {
  61682. lind = this.depthSortedParticles[sorted].indicesLength;
  61683. sind = this.depthSortedParticles[sorted].ind;
  61684. for (var i = 0; i < lind; i++) {
  61685. this._indices32[sid] = this._indices[sind + i];
  61686. sid++;
  61687. }
  61688. }
  61689. this.mesh.updateIndices(this._indices32);
  61690. }
  61691. }
  61692. if (this._computeBoundingBox) {
  61693. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  61694. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  61695. }
  61696. this.afterUpdateParticles(start, end, update);
  61697. return this;
  61698. };
  61699. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  61700. this._halfroll = this._roll * 0.5;
  61701. this._halfpitch = this._pitch * 0.5;
  61702. this._halfyaw = this._yaw * 0.5;
  61703. this._sinRoll = Math.sin(this._halfroll);
  61704. this._cosRoll = Math.cos(this._halfroll);
  61705. this._sinPitch = Math.sin(this._halfpitch);
  61706. this._cosPitch = Math.cos(this._halfpitch);
  61707. this._sinYaw = Math.sin(this._halfyaw);
  61708. this._cosYaw = Math.cos(this._halfyaw);
  61709. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  61710. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  61711. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  61712. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  61713. };
  61714. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  61715. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  61716. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  61717. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  61718. this._rotMatrix.m[3] = 0;
  61719. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  61720. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  61721. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  61722. this._rotMatrix.m[7] = 0;
  61723. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  61724. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  61725. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  61726. this._rotMatrix.m[11] = 0;
  61727. this._rotMatrix.m[12] = 0;
  61728. this._rotMatrix.m[13] = 0;
  61729. this._rotMatrix.m[14] = 0;
  61730. this._rotMatrix.m[15] = 1.0;
  61731. };
  61732. /**
  61733. * Disposes the SPS.
  61734. */
  61735. SolidParticleSystem.prototype.dispose = function () {
  61736. this.mesh.dispose();
  61737. this.vars = null;
  61738. // drop references to internal big arrays for the GC
  61739. this._positions = null;
  61740. this._indices = null;
  61741. this._normals = null;
  61742. this._uvs = null;
  61743. this._colors = null;
  61744. this._indices32 = null;
  61745. this._positions32 = null;
  61746. this._normals32 = null;
  61747. this._fixedNormal32 = null;
  61748. this._uvs32 = null;
  61749. this._colors32 = null;
  61750. this.pickedParticles = null;
  61751. };
  61752. /**
  61753. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  61754. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61755. * @returns the SPS.
  61756. */
  61757. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  61758. if (!this._isVisibilityBoxLocked) {
  61759. this.mesh.refreshBoundingInfo();
  61760. }
  61761. return this;
  61762. };
  61763. /**
  61764. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  61765. * @param size the size (float) of the visibility box
  61766. * note : this doesn't lock the SPS mesh bounding box.
  61767. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61768. */
  61769. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  61770. var vis = size / 2;
  61771. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  61772. };
  61773. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  61774. /**
  61775. * Gets whether the SPS as always visible or not
  61776. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61777. */
  61778. get: function () {
  61779. return this._alwaysVisible;
  61780. },
  61781. /**
  61782. * Sets the SPS as always visible or not
  61783. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61784. */
  61785. set: function (val) {
  61786. this._alwaysVisible = val;
  61787. this.mesh.alwaysSelectAsActiveMesh = val;
  61788. },
  61789. enumerable: true,
  61790. configurable: true
  61791. });
  61792. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  61793. /**
  61794. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61795. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61796. */
  61797. get: function () {
  61798. return this._isVisibilityBoxLocked;
  61799. },
  61800. /**
  61801. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61802. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61803. */
  61804. set: function (val) {
  61805. this._isVisibilityBoxLocked = val;
  61806. var boundingInfo = this.mesh.getBoundingInfo();
  61807. boundingInfo.isLocked = val;
  61808. },
  61809. enumerable: true,
  61810. configurable: true
  61811. });
  61812. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  61813. /**
  61814. * Gets if `setParticles()` computes the particle rotations or not.
  61815. * Default value : true. The SPS is faster when it's set to false.
  61816. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61817. */
  61818. get: function () {
  61819. return this._computeParticleRotation;
  61820. },
  61821. /**
  61822. * Tells to `setParticles()` to compute the particle rotations or not.
  61823. * Default value : true. The SPS is faster when it's set to false.
  61824. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61825. */
  61826. set: function (val) {
  61827. this._computeParticleRotation = val;
  61828. },
  61829. enumerable: true,
  61830. configurable: true
  61831. });
  61832. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  61833. /**
  61834. * Gets if `setParticles()` computes the particle colors or not.
  61835. * Default value : true. The SPS is faster when it's set to false.
  61836. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61837. */
  61838. get: function () {
  61839. return this._computeParticleColor;
  61840. },
  61841. /**
  61842. * Tells to `setParticles()` to compute the particle colors or not.
  61843. * Default value : true. The SPS is faster when it's set to false.
  61844. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61845. */
  61846. set: function (val) {
  61847. this._computeParticleColor = val;
  61848. },
  61849. enumerable: true,
  61850. configurable: true
  61851. });
  61852. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  61853. /**
  61854. * Gets if `setParticles()` computes the particle textures or not.
  61855. * Default value : true. The SPS is faster when it's set to false.
  61856. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  61857. */
  61858. get: function () {
  61859. return this._computeParticleTexture;
  61860. },
  61861. set: function (val) {
  61862. this._computeParticleTexture = val;
  61863. },
  61864. enumerable: true,
  61865. configurable: true
  61866. });
  61867. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  61868. /**
  61869. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  61870. * Default value : false. The SPS is faster when it's set to false.
  61871. * Note : the particle custom vertex positions aren't stored values.
  61872. */
  61873. get: function () {
  61874. return this._computeParticleVertex;
  61875. },
  61876. /**
  61877. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  61878. * Default value : false. The SPS is faster when it's set to false.
  61879. * Note : the particle custom vertex positions aren't stored values.
  61880. */
  61881. set: function (val) {
  61882. this._computeParticleVertex = val;
  61883. },
  61884. enumerable: true,
  61885. configurable: true
  61886. });
  61887. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  61888. /**
  61889. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  61890. */
  61891. get: function () {
  61892. return this._computeBoundingBox;
  61893. },
  61894. /**
  61895. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  61896. */
  61897. set: function (val) {
  61898. this._computeBoundingBox = val;
  61899. },
  61900. enumerable: true,
  61901. configurable: true
  61902. });
  61903. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  61904. /**
  61905. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  61906. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61907. * Default : `true`
  61908. */
  61909. get: function () {
  61910. return this._depthSortParticles;
  61911. },
  61912. /**
  61913. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  61914. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61915. * Default : `true`
  61916. */
  61917. set: function (val) {
  61918. this._depthSortParticles = val;
  61919. },
  61920. enumerable: true,
  61921. configurable: true
  61922. });
  61923. // =======================================================================
  61924. // Particle behavior logic
  61925. // these following methods may be overwritten by the user to fit his needs
  61926. /**
  61927. * This function does nothing. It may be overwritten to set all the particle first values.
  61928. * The SPS doesn't call this function, you may have to call it by your own.
  61929. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61930. */
  61931. SolidParticleSystem.prototype.initParticles = function () {
  61932. };
  61933. /**
  61934. * This function does nothing. It may be overwritten to recycle a particle.
  61935. * The SPS doesn't call this function, you may have to call it by your own.
  61936. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61937. * @param particle The particle to recycle
  61938. * @returns the recycled particle
  61939. */
  61940. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  61941. return particle;
  61942. };
  61943. /**
  61944. * Updates a particle : this function should be overwritten by the user.
  61945. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  61946. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61947. * @example : just set a particle position or velocity and recycle conditions
  61948. * @param particle The particle to update
  61949. * @returns the updated particle
  61950. */
  61951. SolidParticleSystem.prototype.updateParticle = function (particle) {
  61952. return particle;
  61953. };
  61954. /**
  61955. * Updates a vertex of a particle : it can be overwritten by the user.
  61956. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  61957. * @param particle the current particle
  61958. * @param vertex the current index of the current particle
  61959. * @param pt the index of the current vertex in the particle shape
  61960. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  61961. * @example : just set a vertex particle position
  61962. * @returns the updated vertex
  61963. */
  61964. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  61965. return vertex;
  61966. };
  61967. /**
  61968. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  61969. * This does nothing and may be overwritten by the user.
  61970. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61971. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61972. * @param update the boolean update value actually passed to setParticles()
  61973. */
  61974. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  61975. };
  61976. /**
  61977. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  61978. * This will be passed three parameters.
  61979. * This does nothing and may be overwritten by the user.
  61980. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61981. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61982. * @param update the boolean update value actually passed to setParticles()
  61983. */
  61984. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  61985. };
  61986. return SolidParticleSystem;
  61987. }());
  61988. BABYLON.SolidParticleSystem = SolidParticleSystem;
  61989. })(BABYLON || (BABYLON = {}));
  61990. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  61991. var BABYLON;
  61992. (function (BABYLON) {
  61993. /**
  61994. * Class containing static functions to help procedurally build meshes
  61995. */
  61996. var MeshBuilder = /** @class */ (function () {
  61997. function MeshBuilder() {
  61998. }
  61999. MeshBuilder.updateSideOrientation = function (orientation) {
  62000. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62001. return BABYLON.Mesh.DOUBLESIDE;
  62002. }
  62003. if (orientation === undefined || orientation === null) {
  62004. return BABYLON.Mesh.FRONTSIDE;
  62005. }
  62006. return orientation;
  62007. };
  62008. /**
  62009. * Creates a box mesh
  62010. * * The parameter `size` sets the size (float) of each box side (default 1)
  62011. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62012. * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements)
  62013. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62014. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62015. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62016. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62017. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62018. * @param name defines the name of the mesh
  62019. * @param options defines the options used to create the mesh
  62020. * @param scene defines the hosting scene
  62021. * @returns the box mesh
  62022. */
  62023. MeshBuilder.CreateBox = function (name, options, scene) {
  62024. if (scene === void 0) { scene = null; }
  62025. var box = new BABYLON.Mesh(name, scene);
  62026. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62027. box._originalBuilderSideOrientation = options.sideOrientation;
  62028. var vertexData = BABYLON.VertexData.CreateBox(options);
  62029. vertexData.applyToMesh(box, options.updatable);
  62030. return box;
  62031. };
  62032. /**
  62033. * Creates a sphere mesh
  62034. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62035. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  62036. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62037. * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  62038. * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude)
  62039. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62040. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62041. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62042. * @param name defines the name of the mesh
  62043. * @param options defines the options used to create the mesh
  62044. * @param scene defines the hosting scene
  62045. * @returns the sphere mesh
  62046. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62047. */
  62048. MeshBuilder.CreateSphere = function (name, options, scene) {
  62049. var sphere = new BABYLON.Mesh(name, scene);
  62050. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62051. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62052. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62053. vertexData.applyToMesh(sphere, options.updatable);
  62054. return sphere;
  62055. };
  62056. /**
  62057. * Creates a plane polygonal mesh. By default, this is a disc
  62058. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62059. * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
  62060. * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  62061. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62062. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62063. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62064. * @param name defines the name of the mesh
  62065. * @param options defines the options used to create the mesh
  62066. * @param scene defines the hosting scene
  62067. * @returns the plane polygonal mesh
  62068. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62069. */
  62070. MeshBuilder.CreateDisc = function (name, options, scene) {
  62071. if (scene === void 0) { scene = null; }
  62072. var disc = new BABYLON.Mesh(name, scene);
  62073. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62074. disc._originalBuilderSideOrientation = options.sideOrientation;
  62075. var vertexData = BABYLON.VertexData.CreateDisc(options);
  62076. vertexData.applyToMesh(disc, options.updatable);
  62077. return disc;
  62078. };
  62079. /**
  62080. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  62081. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  62082. * * 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`)
  62083. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  62084. * * 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
  62085. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62086. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62087. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62088. * @param name defines the name of the mesh
  62089. * @param options defines the options used to create the mesh
  62090. * @param scene defines the hosting scene
  62091. * @returns the icosahedron mesh
  62092. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  62093. */
  62094. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  62095. var sphere = new BABYLON.Mesh(name, scene);
  62096. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62097. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62098. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  62099. vertexData.applyToMesh(sphere, options.updatable);
  62100. return sphere;
  62101. };
  62102. ;
  62103. /**
  62104. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62105. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  62106. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  62107. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  62108. * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path
  62109. * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11
  62110. * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  62111. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62112. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62113. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62114. * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones
  62115. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  62116. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  62117. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  62118. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62119. * @param name defines the name of the mesh
  62120. * @param options defines the options used to create the mesh
  62121. * @param scene defines the hosting scene
  62122. * @returns the ribbon mesh
  62123. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  62124. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62125. */
  62126. MeshBuilder.CreateRibbon = function (name, options, scene) {
  62127. if (scene === void 0) { scene = null; }
  62128. var pathArray = options.pathArray;
  62129. var closeArray = options.closeArray;
  62130. var closePath = options.closePath;
  62131. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62132. var instance = options.instance;
  62133. var updatable = options.updatable;
  62134. if (instance) { // existing ribbon instance update
  62135. // positionFunction : ribbon case
  62136. // only pathArray and sideOrientation parameters are taken into account for positions update
  62137. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  62138. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  62139. var positionFunction = function (positions) {
  62140. var minlg = pathArray[0].length;
  62141. var i = 0;
  62142. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  62143. for (var si = 1; si <= ns; si++) {
  62144. for (var p = 0; p < pathArray.length; p++) {
  62145. var path = pathArray[p];
  62146. var l = path.length;
  62147. minlg = (minlg < l) ? minlg : l;
  62148. var j = 0;
  62149. while (j < minlg) {
  62150. positions[i] = path[j].x;
  62151. positions[i + 1] = path[j].y;
  62152. positions[i + 2] = path[j].z;
  62153. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  62154. BABYLON.Tmp.Vector3[0].x = path[j].x;
  62155. }
  62156. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  62157. BABYLON.Tmp.Vector3[1].x = path[j].x;
  62158. }
  62159. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  62160. BABYLON.Tmp.Vector3[0].y = path[j].y;
  62161. }
  62162. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  62163. BABYLON.Tmp.Vector3[1].y = path[j].y;
  62164. }
  62165. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  62166. BABYLON.Tmp.Vector3[0].z = path[j].z;
  62167. }
  62168. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  62169. BABYLON.Tmp.Vector3[1].z = path[j].z;
  62170. }
  62171. j++;
  62172. i += 3;
  62173. }
  62174. if (instance._closePath) {
  62175. positions[i] = path[0].x;
  62176. positions[i + 1] = path[0].y;
  62177. positions[i + 2] = path[0].z;
  62178. i += 3;
  62179. }
  62180. }
  62181. }
  62182. };
  62183. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62184. positionFunction(positions);
  62185. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  62186. instance._boundingInfo.update(instance._worldMatrix);
  62187. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62188. if (options.colors) {
  62189. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62190. for (var c = 0; c < options.colors.length; c++) {
  62191. colors[c * 4] = options.colors[c].r;
  62192. colors[c * 4 + 1] = options.colors[c].g;
  62193. colors[c * 4 + 2] = options.colors[c].b;
  62194. colors[c * 4 + 3] = options.colors[c].a;
  62195. }
  62196. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  62197. }
  62198. if (options.uvs) {
  62199. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62200. for (var i = 0; i < options.uvs.length; i++) {
  62201. uvs[i * 2] = options.uvs[i].x;
  62202. uvs[i * 2 + 1] = options.uvs[i].y;
  62203. }
  62204. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  62205. }
  62206. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  62207. var indices = instance.getIndices();
  62208. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62209. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  62210. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  62211. if (instance._closePath) {
  62212. var indexFirst = 0;
  62213. var indexLast = 0;
  62214. for (var p = 0; p < pathArray.length; p++) {
  62215. indexFirst = instance._idx[p] * 3;
  62216. if (p + 1 < pathArray.length) {
  62217. indexLast = (instance._idx[p + 1] - 1) * 3;
  62218. }
  62219. else {
  62220. indexLast = normals.length - 3;
  62221. }
  62222. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  62223. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  62224. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  62225. normals[indexLast] = normals[indexFirst];
  62226. normals[indexLast + 1] = normals[indexFirst + 1];
  62227. normals[indexLast + 2] = normals[indexFirst + 2];
  62228. }
  62229. }
  62230. if (!(instance.areNormalsFrozen)) {
  62231. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  62232. }
  62233. }
  62234. return instance;
  62235. }
  62236. else { // new ribbon creation
  62237. var ribbon = new BABYLON.Mesh(name, scene);
  62238. ribbon._originalBuilderSideOrientation = sideOrientation;
  62239. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  62240. if (closePath) {
  62241. ribbon._idx = vertexData._idx;
  62242. }
  62243. ribbon._closePath = closePath;
  62244. ribbon._closeArray = closeArray;
  62245. vertexData.applyToMesh(ribbon, updatable);
  62246. return ribbon;
  62247. }
  62248. };
  62249. /**
  62250. * Creates a cylinder or a cone mesh
  62251. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  62252. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  62253. * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  62254. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  62255. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  62256. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  62257. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  62258. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  62259. * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  62260. * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  62261. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  62262. * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  62263. * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  62264. * * If `enclose` is false, a ring surface is one element.
  62265. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  62266. * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  62267. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62268. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62269. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62270. * @param name defines the name of the mesh
  62271. * @param options defines the options used to create the mesh
  62272. * @param scene defines the hosting scene
  62273. * @returns the cylinder mesh
  62274. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  62275. */
  62276. MeshBuilder.CreateCylinder = function (name, options, scene) {
  62277. var cylinder = new BABYLON.Mesh(name, scene);
  62278. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62279. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  62280. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  62281. vertexData.applyToMesh(cylinder, options.updatable);
  62282. return cylinder;
  62283. };
  62284. /**
  62285. * Creates a torus mesh
  62286. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  62287. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  62288. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  62289. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62290. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62291. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62292. * @param name defines the name of the mesh
  62293. * @param options defines the options used to create the mesh
  62294. * @param scene defines the hosting scene
  62295. * @returns the torus mesh
  62296. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  62297. */
  62298. MeshBuilder.CreateTorus = function (name, options, scene) {
  62299. var torus = new BABYLON.Mesh(name, scene);
  62300. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62301. torus._originalBuilderSideOrientation = options.sideOrientation;
  62302. var vertexData = BABYLON.VertexData.CreateTorus(options);
  62303. vertexData.applyToMesh(torus, options.updatable);
  62304. return torus;
  62305. };
  62306. /**
  62307. * Creates a torus knot mesh
  62308. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  62309. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  62310. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  62311. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  62312. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62313. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62314. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62315. * @param name defines the name of the mesh
  62316. * @param options defines the options used to create the mesh
  62317. * @param scene defines the hosting scene
  62318. * @returns the torus knot mesh
  62319. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  62320. */
  62321. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  62322. var torusKnot = new BABYLON.Mesh(name, scene);
  62323. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62324. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  62325. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  62326. vertexData.applyToMesh(torusKnot, options.updatable);
  62327. return torusKnot;
  62328. };
  62329. /**
  62330. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  62331. * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter
  62332. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  62333. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  62334. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  62335. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  62336. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  62337. * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  62338. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  62339. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62340. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  62341. * @param name defines the name of the new line system
  62342. * @param options defines the options used to create the line system
  62343. * @param scene defines the hosting scene
  62344. * @returns a new line system mesh
  62345. */
  62346. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  62347. var instance = options.instance;
  62348. var lines = options.lines;
  62349. var colors = options.colors;
  62350. if (instance) { // lines update
  62351. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62352. var vertexColor;
  62353. var lineColors;
  62354. if (colors) {
  62355. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62356. }
  62357. var i = 0;
  62358. var c = 0;
  62359. for (var l = 0; l < lines.length; l++) {
  62360. var points = lines[l];
  62361. for (var p = 0; p < points.length; p++) {
  62362. positions[i] = points[p].x;
  62363. positions[i + 1] = points[p].y;
  62364. positions[i + 2] = points[p].z;
  62365. if (colors && vertexColor) {
  62366. lineColors = colors[l];
  62367. vertexColor[c] = lineColors[p].r;
  62368. vertexColor[c + 1] = lineColors[p].g;
  62369. vertexColor[c + 2] = lineColors[p].b;
  62370. vertexColor[c + 3] = lineColors[p].a;
  62371. c += 4;
  62372. }
  62373. i += 3;
  62374. }
  62375. }
  62376. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62377. if (colors && vertexColor) {
  62378. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  62379. }
  62380. return instance;
  62381. }
  62382. // line system creation
  62383. var useVertexColor = (colors) ? true : false;
  62384. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  62385. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  62386. vertexData.applyToMesh(lineSystem, options.updatable);
  62387. return lineSystem;
  62388. };
  62389. /**
  62390. * Creates a line mesh
  62391. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter
  62392. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62393. * * The parameter `points` is an array successive Vector3
  62394. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  62395. * * The optional parameter `colors` is an array of successive Color4, one per line point
  62396. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  62397. * * When updating an instance, remember that only point positions can change, not the number of points
  62398. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62399. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62400. * @param name defines the name of the new line system
  62401. * @param options defines the options used to create the line system
  62402. * @param scene defines the hosting scene
  62403. * @returns a new line mesh
  62404. */
  62405. MeshBuilder.CreateLines = function (name, options, scene) {
  62406. if (scene === void 0) { scene = null; }
  62407. var colors = (options.colors) ? [options.colors] : null;
  62408. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62409. return lines;
  62410. };
  62411. /**
  62412. * Creates a dashed line mesh
  62413. * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter
  62414. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62415. * * The parameter `points` is an array successive Vector3
  62416. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62417. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62418. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62419. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  62420. * * When updating an instance, remember that only point positions can change, not the number of points
  62421. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62422. * @param name defines the name of the mesh
  62423. * @param options defines the options used to create the mesh
  62424. * @param scene defines the hosting scene
  62425. * @returns the dashed line mesh
  62426. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62427. */
  62428. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62429. if (scene === void 0) { scene = null; }
  62430. var points = options.points;
  62431. var instance = options.instance;
  62432. var gapSize = options.gapSize || 1;
  62433. var dashSize = options.dashSize || 3;
  62434. if (instance) { // dashed lines update
  62435. var positionFunction = function (positions) {
  62436. var curvect = BABYLON.Vector3.Zero();
  62437. var nbSeg = positions.length / 6;
  62438. var lg = 0;
  62439. var nb = 0;
  62440. var shft = 0;
  62441. var dashshft = 0;
  62442. var curshft = 0;
  62443. var p = 0;
  62444. var i = 0;
  62445. var j = 0;
  62446. for (i = 0; i < points.length - 1; i++) {
  62447. points[i + 1].subtractToRef(points[i], curvect);
  62448. lg += curvect.length();
  62449. }
  62450. shft = lg / nbSeg;
  62451. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62452. for (i = 0; i < points.length - 1; i++) {
  62453. points[i + 1].subtractToRef(points[i], curvect);
  62454. nb = Math.floor(curvect.length() / shft);
  62455. curvect.normalize();
  62456. j = 0;
  62457. while (j < nb && p < positions.length) {
  62458. curshft = shft * j;
  62459. positions[p] = points[i].x + curshft * curvect.x;
  62460. positions[p + 1] = points[i].y + curshft * curvect.y;
  62461. positions[p + 2] = points[i].z + curshft * curvect.z;
  62462. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62463. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62464. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62465. p += 6;
  62466. j++;
  62467. }
  62468. }
  62469. while (p < positions.length) {
  62470. positions[p] = points[i].x;
  62471. positions[p + 1] = points[i].y;
  62472. positions[p + 2] = points[i].z;
  62473. p += 3;
  62474. }
  62475. };
  62476. instance.updateMeshPositions(positionFunction, false);
  62477. return instance;
  62478. }
  62479. // dashed lines creation
  62480. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62481. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62482. vertexData.applyToMesh(dashedLines, options.updatable);
  62483. dashedLines.dashSize = dashSize;
  62484. dashedLines.gapSize = gapSize;
  62485. return dashedLines;
  62486. };
  62487. /**
  62488. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62489. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  62490. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62491. * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  62492. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62493. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  62494. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  62495. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62496. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62497. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62498. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62499. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62500. * @param name defines the name of the mesh
  62501. * @param options defines the options used to create the mesh
  62502. * @param scene defines the hosting scene
  62503. * @returns the extruded shape mesh
  62504. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62505. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62506. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62507. */
  62508. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62509. if (scene === void 0) { scene = null; }
  62510. var path = options.path;
  62511. var shape = options.shape;
  62512. var scale = options.scale || 1;
  62513. var rotation = options.rotation || 0;
  62514. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62515. var updatable = options.updatable;
  62516. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62517. var instance = options.instance || null;
  62518. var invertUV = options.invertUV || false;
  62519. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);
  62520. };
  62521. /**
  62522. * Creates an custom extruded shape mesh.
  62523. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62524. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  62525. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62526. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  62527. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62528. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  62529. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62530. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62531. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62532. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  62533. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  62534. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62535. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62536. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62537. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62538. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62539. * @param name defines the name of the mesh
  62540. * @param options defines the options used to create the mesh
  62541. * @param scene defines the hosting scene
  62542. * @returns the custom extruded shape mesh
  62543. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  62544. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62545. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62546. */
  62547. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  62548. var path = options.path;
  62549. var shape = options.shape;
  62550. var scaleFunction = options.scaleFunction || (function () { return 1; });
  62551. var rotationFunction = options.rotationFunction || (function () { return 0; });
  62552. var ribbonCloseArray = options.ribbonCloseArray || false;
  62553. var ribbonClosePath = options.ribbonClosePath || false;
  62554. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62555. var updatable = options.updatable;
  62556. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62557. var instance = options.instance;
  62558. var invertUV = options.invertUV || false;
  62559. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);
  62560. };
  62561. /**
  62562. * Creates lathe mesh.
  62563. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  62564. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  62565. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  62566. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  62567. * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape
  62568. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  62569. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  62570. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62571. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62572. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62573. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62574. * @param name defines the name of the mesh
  62575. * @param options defines the options used to create the mesh
  62576. * @param scene defines the hosting scene
  62577. * @returns the lathe mesh
  62578. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  62579. */
  62580. MeshBuilder.CreateLathe = function (name, options, scene) {
  62581. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  62582. var closed = (options.closed === undefined) ? true : options.closed;
  62583. var shape = options.shape;
  62584. var radius = options.radius || 1;
  62585. var tessellation = options.tessellation || 64;
  62586. var updatable = options.updatable;
  62587. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62588. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62589. var pi2 = Math.PI * 2;
  62590. var paths = new Array();
  62591. var invertUV = options.invertUV || false;
  62592. var i = 0;
  62593. var p = 0;
  62594. var step = pi2 / tessellation * arc;
  62595. var rotated;
  62596. var path = new Array();
  62597. for (i = 0; i <= tessellation; i++) {
  62598. var path = [];
  62599. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  62600. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  62601. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  62602. }
  62603. for (p = 0; p < shape.length; p++) {
  62604. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  62605. path.push(rotated);
  62606. }
  62607. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  62608. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  62609. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  62610. }
  62611. paths.push(path);
  62612. }
  62613. // lathe ribbon
  62614. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62615. return lathe;
  62616. };
  62617. /**
  62618. * Creates a plane mesh
  62619. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  62620. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  62621. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  62622. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62623. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62624. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62625. * @param name defines the name of the mesh
  62626. * @param options defines the options used to create the mesh
  62627. * @param scene defines the hosting scene
  62628. * @returns the plane mesh
  62629. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62630. */
  62631. MeshBuilder.CreatePlane = function (name, options, scene) {
  62632. var plane = new BABYLON.Mesh(name, scene);
  62633. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62634. plane._originalBuilderSideOrientation = options.sideOrientation;
  62635. var vertexData = BABYLON.VertexData.CreatePlane(options);
  62636. vertexData.applyToMesh(plane, options.updatable);
  62637. if (options.sourcePlane) {
  62638. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  62639. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  62640. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  62641. plane.rotate(vectorProduct, product);
  62642. }
  62643. return plane;
  62644. };
  62645. /**
  62646. * Creates a ground mesh
  62647. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  62648. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  62649. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62650. * @param name defines the name of the mesh
  62651. * @param options defines the options used to create the mesh
  62652. * @param scene defines the hosting scene
  62653. * @returns the ground mesh
  62654. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62655. */
  62656. MeshBuilder.CreateGround = function (name, options, scene) {
  62657. var ground = new BABYLON.GroundMesh(name, scene);
  62658. ground._setReady(false);
  62659. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  62660. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  62661. ground._width = options.width || 1;
  62662. ground._height = options.height || 1;
  62663. ground._maxX = ground._width / 2;
  62664. ground._maxZ = ground._height / 2;
  62665. ground._minX = -ground._maxX;
  62666. ground._minZ = -ground._maxZ;
  62667. var vertexData = BABYLON.VertexData.CreateGround(options);
  62668. vertexData.applyToMesh(ground, options.updatable);
  62669. ground._setReady(true);
  62670. return ground;
  62671. };
  62672. /**
  62673. * Creates a tiled ground mesh
  62674. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  62675. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  62676. * * The parameter `subdivisions` is a javascript 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
  62677. * * The parameter `precision` is a javascript 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
  62678. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62679. * @param name defines the name of the mesh
  62680. * @param options defines the options used to create the mesh
  62681. * @param scene defines the hosting scene
  62682. * @returns the tiled ground mesh
  62683. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  62684. */
  62685. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  62686. var tiledGround = new BABYLON.Mesh(name, scene);
  62687. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  62688. vertexData.applyToMesh(tiledGround, options.updatable);
  62689. return tiledGround;
  62690. };
  62691. /**
  62692. * Creates a ground mesh from a height map
  62693. * * The parameter `url` sets the URL of the height map image resource.
  62694. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  62695. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  62696. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  62697. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  62698. * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  62699. * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  62700. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62701. * @param name defines the name of the mesh
  62702. * @param url defines the url to the height map
  62703. * @param options defines the options used to create the mesh
  62704. * @param scene defines the hosting scene
  62705. * @returns the ground mesh
  62706. * @see http://doc.babylonjs.com/babylon101/height_map
  62707. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  62708. */
  62709. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  62710. var width = options.width || 10.0;
  62711. var height = options.height || 10.0;
  62712. var subdivisions = options.subdivisions || 1 | 0;
  62713. var minHeight = options.minHeight || 0.0;
  62714. var maxHeight = options.maxHeight || 1.0;
  62715. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  62716. var updatable = options.updatable;
  62717. var onReady = options.onReady;
  62718. var ground = new BABYLON.GroundMesh(name, scene);
  62719. ground._subdivisionsX = subdivisions;
  62720. ground._subdivisionsY = subdivisions;
  62721. ground._width = width;
  62722. ground._height = height;
  62723. ground._maxX = ground._width / 2.0;
  62724. ground._maxZ = ground._height / 2.0;
  62725. ground._minX = -ground._maxX;
  62726. ground._minZ = -ground._maxZ;
  62727. ground._setReady(false);
  62728. var onload = function (img) {
  62729. // Getting height map data
  62730. var canvas = document.createElement("canvas");
  62731. var context = canvas.getContext("2d");
  62732. if (!context) {
  62733. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  62734. }
  62735. if (scene.isDisposed) {
  62736. return;
  62737. }
  62738. var bufferWidth = img.width;
  62739. var bufferHeight = img.height;
  62740. canvas.width = bufferWidth;
  62741. canvas.height = bufferHeight;
  62742. context.drawImage(img, 0, 0);
  62743. // Create VertexData from map data
  62744. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  62745. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  62746. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  62747. width: width, height: height,
  62748. subdivisions: subdivisions,
  62749. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  62750. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  62751. });
  62752. vertexData.applyToMesh(ground, updatable);
  62753. //execute ready callback, if set
  62754. if (onReady) {
  62755. onReady(ground);
  62756. }
  62757. ground._setReady(true);
  62758. };
  62759. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  62760. return ground;
  62761. };
  62762. /**
  62763. * Creates a polygon mesh
  62764. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  62765. * * 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
  62766. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62767. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62768. * * 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)
  62769. * * Remember you can only change the shape positions, not their number when updating a polygon
  62770. * @param name defines the name of the mesh
  62771. * @param options defines the options used to create the mesh
  62772. * @param scene defines the hosting scene
  62773. * @returns the polygon mesh
  62774. */
  62775. MeshBuilder.CreatePolygon = function (name, options, scene) {
  62776. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62777. var shape = options.shape;
  62778. var holes = options.holes || [];
  62779. var depth = options.depth || 0;
  62780. var contours = [];
  62781. var hole = [];
  62782. for (var i = 0; i < shape.length; i++) {
  62783. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  62784. }
  62785. var epsilon = 0.00000001;
  62786. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  62787. contours.pop();
  62788. }
  62789. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  62790. for (var hNb = 0; hNb < holes.length; hNb++) {
  62791. hole = [];
  62792. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  62793. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  62794. }
  62795. polygonTriangulation.addHole(hole);
  62796. }
  62797. var polygon = polygonTriangulation.build(options.updatable, depth);
  62798. polygon._originalBuilderSideOrientation = options.sideOrientation;
  62799. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  62800. vertexData.applyToMesh(polygon, options.updatable);
  62801. return polygon;
  62802. };
  62803. ;
  62804. /**
  62805. * Creates an extruded polygon mesh, with depth in the Y direction.
  62806. * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)
  62807. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62808. * @param name defines the name of the mesh
  62809. * @param options defines the options used to create the mesh
  62810. * @param scene defines the hosting scene
  62811. * @returns the polygon mesh
  62812. */
  62813. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  62814. return MeshBuilder.CreatePolygon(name, options, scene);
  62815. };
  62816. ;
  62817. /**
  62818. * Creates a tube mesh.
  62819. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62820. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  62821. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  62822. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  62823. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  62824. * * 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. It must return a radius value (positive float)
  62825. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  62826. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  62827. * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  62828. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62829. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62830. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62831. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62832. * @param name defines the name of the mesh
  62833. * @param options defines the options used to create the mesh
  62834. * @param scene defines the hosting scene
  62835. * @returns the tube mesh
  62836. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62837. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  62838. */
  62839. MeshBuilder.CreateTube = function (name, options, scene) {
  62840. var path = options.path;
  62841. var instance = options.instance;
  62842. var radius = 1.0;
  62843. if (instance) {
  62844. radius = instance.radius;
  62845. }
  62846. if (options.radius !== undefined) {
  62847. radius = options.radius;
  62848. }
  62849. ;
  62850. var tessellation = options.tessellation || 64 | 0;
  62851. var radiusFunction = options.radiusFunction || null;
  62852. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62853. var invertUV = options.invertUV || false;
  62854. var updatable = options.updatable;
  62855. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62856. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  62857. // tube geometry
  62858. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  62859. var tangents = path3D.getTangents();
  62860. var normals = path3D.getNormals();
  62861. var distances = path3D.getDistances();
  62862. var pi2 = Math.PI * 2;
  62863. var step = pi2 / tessellation * arc;
  62864. var returnRadius = function () { return radius; };
  62865. var radiusFunctionFinal = radiusFunction || returnRadius;
  62866. var circlePath;
  62867. var rad;
  62868. var normal;
  62869. var rotated;
  62870. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62871. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62872. for (var i = 0; i < path.length; i++) {
  62873. rad = radiusFunctionFinal(i, distances[i]); // current radius
  62874. circlePath = Array(); // current circle array
  62875. normal = normals[i]; // current normal
  62876. for (var t = 0; t < tessellation; t++) {
  62877. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  62878. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  62879. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  62880. rotated.scaleInPlace(rad).addInPlace(path[i]);
  62881. circlePath[t] = rotated;
  62882. }
  62883. circlePaths[index] = circlePath;
  62884. index++;
  62885. }
  62886. // cap
  62887. var capPath = function (nbPoints, pathIndex) {
  62888. var pointCap = Array();
  62889. for (var i = 0; i < nbPoints; i++) {
  62890. pointCap.push(path[pathIndex]);
  62891. }
  62892. return pointCap;
  62893. };
  62894. switch (cap) {
  62895. case BABYLON.Mesh.NO_CAP:
  62896. break;
  62897. case BABYLON.Mesh.CAP_START:
  62898. circlePaths[0] = capPath(tessellation, 0);
  62899. circlePaths[1] = circlePaths[2].slice(0);
  62900. break;
  62901. case BABYLON.Mesh.CAP_END:
  62902. circlePaths[index] = circlePaths[index - 1].slice(0);
  62903. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62904. break;
  62905. case BABYLON.Mesh.CAP_ALL:
  62906. circlePaths[0] = capPath(tessellation, 0);
  62907. circlePaths[1] = circlePaths[2].slice(0);
  62908. circlePaths[index] = circlePaths[index - 1].slice(0);
  62909. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62910. break;
  62911. default:
  62912. break;
  62913. }
  62914. return circlePaths;
  62915. };
  62916. var path3D;
  62917. var pathArray;
  62918. if (instance) { // tube update
  62919. var arc = options.arc || instance.arc;
  62920. path3D = (instance.path3D).update(path);
  62921. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  62922. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  62923. instance.path3D = path3D;
  62924. instance.pathArray = pathArray;
  62925. instance.arc = arc;
  62926. instance.radius = radius;
  62927. return instance;
  62928. }
  62929. // tube creation
  62930. path3D = new BABYLON.Path3D(path);
  62931. var newPathArray = new Array();
  62932. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62933. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62934. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62935. tube.pathArray = pathArray;
  62936. tube.path3D = path3D;
  62937. tube.tessellation = tessellation;
  62938. tube.cap = cap;
  62939. tube.arc = options.arc;
  62940. tube.radius = radius;
  62941. return tube;
  62942. };
  62943. /**
  62944. * Creates a polyhedron mesh
  62945. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  62946. * * The parameter `size` (positive float, default 1) sets the polygon size
  62947. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62948. * * 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`
  62949. * * 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
  62950. * * 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)`)
  62951. * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62952. * * 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
  62953. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62954. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  62955. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62956. * @param name defines the name of the mesh
  62957. * @param options defines the options used to create the mesh
  62958. * @param scene defines the hosting scene
  62959. * @returns the polyhedron mesh
  62960. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62961. */
  62962. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62963. var polyhedron = new BABYLON.Mesh(name, scene);
  62964. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62965. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62966. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62967. vertexData.applyToMesh(polyhedron, options.updatable);
  62968. return polyhedron;
  62969. };
  62970. /**
  62971. * Creates a decal mesh.
  62972. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal
  62973. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62974. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62975. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62976. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62977. * @param name defines the name of the mesh
  62978. * @param sourceMesh defines the mesh where the decal must be applied
  62979. * @param options defines the options used to create the mesh
  62980. * @param scene defines the hosting scene
  62981. * @returns the decal mesh
  62982. * @see http://doc.babylonjs.com/how_to/decals
  62983. */
  62984. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62985. var indices = sourceMesh.getIndices();
  62986. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62987. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62988. var position = options.position || BABYLON.Vector3.Zero();
  62989. var normal = options.normal || BABYLON.Vector3.Up();
  62990. var size = options.size || BABYLON.Vector3.One();
  62991. var angle = options.angle || 0;
  62992. // Getting correct rotation
  62993. if (!normal) {
  62994. var target = new BABYLON.Vector3(0, 0, 1);
  62995. var camera = sourceMesh.getScene().activeCamera;
  62996. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62997. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62998. }
  62999. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63000. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63001. var pitch = Math.atan2(normal.y, len);
  63002. // Matrix
  63003. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63004. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63005. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63006. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63007. var vertexData = new BABYLON.VertexData();
  63008. vertexData.indices = [];
  63009. vertexData.positions = [];
  63010. vertexData.normals = [];
  63011. vertexData.uvs = [];
  63012. var currentVertexDataIndex = 0;
  63013. var extractDecalVector3 = function (indexId) {
  63014. var result = new BABYLON.PositionNormalVertex();
  63015. if (!indices || !positions || !normals) {
  63016. return result;
  63017. }
  63018. var vertexId = indices[indexId];
  63019. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63020. // Send vector to decal local world
  63021. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63022. // Get normal
  63023. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63024. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63025. return result;
  63026. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63027. var clip = function (vertices, axis) {
  63028. if (vertices.length === 0) {
  63029. return vertices;
  63030. }
  63031. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63032. var clipVertices = function (v0, v1) {
  63033. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63034. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63035. };
  63036. var result = new Array();
  63037. for (var index = 0; index < vertices.length; index += 3) {
  63038. var v1Out;
  63039. var v2Out;
  63040. var v3Out;
  63041. var total = 0;
  63042. var nV1 = null;
  63043. var nV2 = null;
  63044. var nV3 = null;
  63045. var nV4 = null;
  63046. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63047. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63048. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63049. v1Out = d1 > 0;
  63050. v2Out = d2 > 0;
  63051. v3Out = d3 > 0;
  63052. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63053. switch (total) {
  63054. case 0:
  63055. result.push(vertices[index]);
  63056. result.push(vertices[index + 1]);
  63057. result.push(vertices[index + 2]);
  63058. break;
  63059. case 1:
  63060. if (v1Out) {
  63061. nV1 = vertices[index + 1];
  63062. nV2 = vertices[index + 2];
  63063. nV3 = clipVertices(vertices[index], nV1);
  63064. nV4 = clipVertices(vertices[index], nV2);
  63065. }
  63066. if (v2Out) {
  63067. nV1 = vertices[index];
  63068. nV2 = vertices[index + 2];
  63069. nV3 = clipVertices(vertices[index + 1], nV1);
  63070. nV4 = clipVertices(vertices[index + 1], nV2);
  63071. result.push(nV3);
  63072. result.push(nV2.clone());
  63073. result.push(nV1.clone());
  63074. result.push(nV2.clone());
  63075. result.push(nV3.clone());
  63076. result.push(nV4);
  63077. break;
  63078. }
  63079. if (v3Out) {
  63080. nV1 = vertices[index];
  63081. nV2 = vertices[index + 1];
  63082. nV3 = clipVertices(vertices[index + 2], nV1);
  63083. nV4 = clipVertices(vertices[index + 2], nV2);
  63084. }
  63085. if (nV1 && nV2 && nV3 && nV4) {
  63086. result.push(nV1.clone());
  63087. result.push(nV2.clone());
  63088. result.push(nV3);
  63089. result.push(nV4);
  63090. result.push(nV3.clone());
  63091. result.push(nV2.clone());
  63092. }
  63093. break;
  63094. case 2:
  63095. if (!v1Out) {
  63096. nV1 = vertices[index].clone();
  63097. nV2 = clipVertices(nV1, vertices[index + 1]);
  63098. nV3 = clipVertices(nV1, vertices[index + 2]);
  63099. result.push(nV1);
  63100. result.push(nV2);
  63101. result.push(nV3);
  63102. }
  63103. if (!v2Out) {
  63104. nV1 = vertices[index + 1].clone();
  63105. nV2 = clipVertices(nV1, vertices[index + 2]);
  63106. nV3 = clipVertices(nV1, vertices[index]);
  63107. result.push(nV1);
  63108. result.push(nV2);
  63109. result.push(nV3);
  63110. }
  63111. if (!v3Out) {
  63112. nV1 = vertices[index + 2].clone();
  63113. nV2 = clipVertices(nV1, vertices[index]);
  63114. nV3 = clipVertices(nV1, vertices[index + 1]);
  63115. result.push(nV1);
  63116. result.push(nV2);
  63117. result.push(nV3);
  63118. }
  63119. break;
  63120. case 3:
  63121. break;
  63122. }
  63123. }
  63124. return result;
  63125. };
  63126. for (var index = 0; index < indices.length; index += 3) {
  63127. var faceVertices = new Array();
  63128. faceVertices.push(extractDecalVector3(index));
  63129. faceVertices.push(extractDecalVector3(index + 1));
  63130. faceVertices.push(extractDecalVector3(index + 2));
  63131. // Clip
  63132. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  63133. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  63134. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  63135. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  63136. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  63137. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  63138. if (faceVertices.length === 0) {
  63139. continue;
  63140. }
  63141. // Add UVs and get back to world
  63142. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  63143. var vertex = faceVertices[vIndex];
  63144. //TODO check for Int32Array | Uint32Array | Uint16Array
  63145. vertexData.indices.push(currentVertexDataIndex);
  63146. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  63147. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  63148. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  63149. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  63150. currentVertexDataIndex++;
  63151. }
  63152. }
  63153. // Return mesh
  63154. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  63155. vertexData.applyToMesh(decal);
  63156. decal.position = position.clone();
  63157. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  63158. return decal;
  63159. };
  63160. // Privates
  63161. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  63162. // extrusion geometry
  63163. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  63164. var tangents = path3D.getTangents();
  63165. var normals = path3D.getNormals();
  63166. var binormals = path3D.getBinormals();
  63167. var distances = path3D.getDistances();
  63168. var angle = 0;
  63169. var returnScale = function () { return scale !== null ? scale : 1; };
  63170. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  63171. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  63172. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  63173. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63174. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63175. for (var i = 0; i < curve.length; i++) {
  63176. var shapePath = new Array();
  63177. var angleStep = rotate(i, distances[i]);
  63178. var scaleRatio = scl(i, distances[i]);
  63179. for (var p = 0; p < shape.length; p++) {
  63180. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  63181. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  63182. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  63183. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  63184. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  63185. shapePath[p] = rotated;
  63186. }
  63187. shapePaths[index] = shapePath;
  63188. angle += angleStep;
  63189. index++;
  63190. }
  63191. // cap
  63192. var capPath = function (shapePath) {
  63193. var pointCap = Array();
  63194. var barycenter = BABYLON.Vector3.Zero();
  63195. var i;
  63196. for (i = 0; i < shapePath.length; i++) {
  63197. barycenter.addInPlace(shapePath[i]);
  63198. }
  63199. barycenter.scaleInPlace(1.0 / shapePath.length);
  63200. for (i = 0; i < shapePath.length; i++) {
  63201. pointCap.push(barycenter);
  63202. }
  63203. return pointCap;
  63204. };
  63205. switch (cap) {
  63206. case BABYLON.Mesh.NO_CAP:
  63207. break;
  63208. case BABYLON.Mesh.CAP_START:
  63209. shapePaths[0] = capPath(shapePaths[2]);
  63210. shapePaths[1] = shapePaths[2];
  63211. break;
  63212. case BABYLON.Mesh.CAP_END:
  63213. shapePaths[index] = shapePaths[index - 1];
  63214. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63215. break;
  63216. case BABYLON.Mesh.CAP_ALL:
  63217. shapePaths[0] = capPath(shapePaths[2]);
  63218. shapePaths[1] = shapePaths[2];
  63219. shapePaths[index] = shapePaths[index - 1];
  63220. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63221. break;
  63222. default:
  63223. break;
  63224. }
  63225. return shapePaths;
  63226. };
  63227. var path3D;
  63228. var pathArray;
  63229. if (instance) { // instance update
  63230. path3D = (instance.path3D).update(curve);
  63231. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  63232. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  63233. return instance;
  63234. }
  63235. // extruded shape creation
  63236. path3D = new BABYLON.Path3D(curve);
  63237. var newShapePaths = new Array();
  63238. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63239. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  63240. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  63241. extrudedGeneric.pathArray = pathArray;
  63242. extrudedGeneric.path3D = path3D;
  63243. extrudedGeneric.cap = cap;
  63244. return extrudedGeneric;
  63245. };
  63246. return MeshBuilder;
  63247. }());
  63248. BABYLON.MeshBuilder = MeshBuilder;
  63249. })(BABYLON || (BABYLON = {}));
  63250. //# sourceMappingURL=babylon.meshBuilder.js.map
  63251. var BABYLON;
  63252. (function (BABYLON) {
  63253. /**
  63254. * Draco compression (https://google.github.io/draco/)
  63255. *
  63256. * This class wraps the Draco module.
  63257. *
  63258. * **Encoder**
  63259. *
  63260. * The encoder is not currently implemented.
  63261. *
  63262. * **Decoder**
  63263. *
  63264. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  63265. *
  63266. * To update the configuration, use the following code:
  63267. * ```javascript
  63268. * BABYLON.DracoCompression.Configuration = {
  63269. * decoder: {
  63270. * wasmUrl: "<url to the WebAssembly library>",
  63271. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  63272. * fallbackUrl: "<url to the fallback JavaScript library>",
  63273. * }
  63274. * };
  63275. * ```
  63276. *
  63277. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  63278. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  63279. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  63280. *
  63281. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  63282. * ```javascript
  63283. * var dracoCompression = new BABYLON.DracoCompression();
  63284. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  63285. * [BABYLON.VertexBuffer.PositionKind]: 0
  63286. * });
  63287. * ```
  63288. *
  63289. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  63290. */
  63291. var DracoCompression = /** @class */ (function () {
  63292. /**
  63293. * Constructor
  63294. */
  63295. function DracoCompression() {
  63296. }
  63297. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  63298. /**
  63299. * Returns true if the decoder is available.
  63300. */
  63301. get: function () {
  63302. if (typeof DracoDecoderModule !== "undefined") {
  63303. return true;
  63304. }
  63305. var decoder = DracoCompression.Configuration.decoder;
  63306. if (decoder) {
  63307. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63308. return true;
  63309. }
  63310. if (decoder.fallbackUrl) {
  63311. return true;
  63312. }
  63313. }
  63314. return false;
  63315. },
  63316. enumerable: true,
  63317. configurable: true
  63318. });
  63319. /**
  63320. * Stop all async operations and release resources.
  63321. */
  63322. DracoCompression.prototype.dispose = function () {
  63323. };
  63324. /**
  63325. * Decode Draco compressed mesh data to vertex data.
  63326. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  63327. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  63328. * @returns A promise that resolves with the decoded vertex data
  63329. */
  63330. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  63331. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  63332. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  63333. var module = wrappedModule.module;
  63334. var vertexData = new BABYLON.VertexData();
  63335. var buffer = new module.DecoderBuffer();
  63336. buffer.Init(dataView, dataView.byteLength);
  63337. var decoder = new module.Decoder();
  63338. var geometry;
  63339. var status;
  63340. try {
  63341. var type = decoder.GetEncodedGeometryType(buffer);
  63342. switch (type) {
  63343. case module.TRIANGULAR_MESH:
  63344. geometry = new module.Mesh();
  63345. status = decoder.DecodeBufferToMesh(buffer, geometry);
  63346. break;
  63347. case module.POINT_CLOUD:
  63348. geometry = new module.PointCloud();
  63349. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  63350. break;
  63351. default:
  63352. throw new Error("Invalid geometry type " + type);
  63353. }
  63354. if (!status.ok() || !geometry.ptr) {
  63355. throw new Error(status.error_msg());
  63356. }
  63357. var numPoints = geometry.num_points();
  63358. if (type === module.TRIANGULAR_MESH) {
  63359. var numFaces = geometry.num_faces();
  63360. var faceIndices = new module.DracoInt32Array();
  63361. try {
  63362. var indices = new Uint32Array(numFaces * 3);
  63363. for (var i = 0; i < numFaces; i++) {
  63364. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  63365. var offset = i * 3;
  63366. indices[offset + 0] = faceIndices.GetValue(0);
  63367. indices[offset + 1] = faceIndices.GetValue(1);
  63368. indices[offset + 2] = faceIndices.GetValue(2);
  63369. }
  63370. vertexData.indices = indices;
  63371. }
  63372. finally {
  63373. module.destroy(faceIndices);
  63374. }
  63375. }
  63376. for (var kind in attributes) {
  63377. var uniqueId = attributes[kind];
  63378. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  63379. var dracoData = new module.DracoFloat32Array();
  63380. try {
  63381. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  63382. var babylonData = new Float32Array(numPoints * attribute.num_components());
  63383. for (var i = 0; i < babylonData.length; i++) {
  63384. babylonData[i] = dracoData.GetValue(i);
  63385. }
  63386. vertexData.set(babylonData, kind);
  63387. }
  63388. finally {
  63389. module.destroy(dracoData);
  63390. }
  63391. }
  63392. }
  63393. finally {
  63394. if (geometry) {
  63395. module.destroy(geometry);
  63396. }
  63397. module.destroy(decoder);
  63398. module.destroy(buffer);
  63399. }
  63400. return vertexData;
  63401. });
  63402. };
  63403. DracoCompression._GetDecoderModule = function () {
  63404. if (!DracoCompression._DecoderModulePromise) {
  63405. var promise = null;
  63406. var config_1 = {};
  63407. if (typeof DracoDecoderModule !== "undefined") {
  63408. promise = Promise.resolve();
  63409. }
  63410. else {
  63411. var decoder = DracoCompression.Configuration.decoder;
  63412. if (decoder) {
  63413. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63414. promise = Promise.all([
  63415. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63416. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63417. config_1.wasmBinary = data;
  63418. })
  63419. ]);
  63420. }
  63421. else if (decoder.fallbackUrl) {
  63422. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63423. }
  63424. }
  63425. }
  63426. if (!promise) {
  63427. throw new Error("Draco decoder module is not available");
  63428. }
  63429. DracoCompression._DecoderModulePromise = promise.then(function () {
  63430. return new Promise(function (resolve) {
  63431. config_1.onModuleLoaded = function (decoderModule) {
  63432. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63433. resolve({ module: decoderModule });
  63434. };
  63435. DracoDecoderModule(config_1);
  63436. });
  63437. });
  63438. }
  63439. return DracoCompression._DecoderModulePromise;
  63440. };
  63441. DracoCompression._LoadScriptAsync = function (url) {
  63442. return new Promise(function (resolve, reject) {
  63443. BABYLON.Tools.LoadScript(url, function () {
  63444. resolve();
  63445. }, function (message) {
  63446. reject(new Error(message));
  63447. });
  63448. });
  63449. };
  63450. DracoCompression._LoadFileAsync = function (url) {
  63451. return new Promise(function (resolve, reject) {
  63452. BABYLON.Tools.LoadFile(url, function (data) {
  63453. resolve(data);
  63454. }, undefined, undefined, true, function (request, exception) {
  63455. reject(exception);
  63456. });
  63457. });
  63458. };
  63459. /**
  63460. * The configuration. Defaults to the following urls:
  63461. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63462. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63463. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63464. */
  63465. DracoCompression.Configuration = {
  63466. decoder: {
  63467. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63468. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63469. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63470. }
  63471. };
  63472. return DracoCompression;
  63473. }());
  63474. BABYLON.DracoCompression = DracoCompression;
  63475. })(BABYLON || (BABYLON = {}));
  63476. //# sourceMappingURL=babylon.dracoCompression.js.map
  63477. var BABYLON;
  63478. (function (BABYLON) {
  63479. var AudioEngine = /** @class */ (function () {
  63480. function AudioEngine() {
  63481. this._audioContext = null;
  63482. this._audioContextInitialized = false;
  63483. this.canUseWebAudio = false;
  63484. this.WarnedWebAudioUnsupported = false;
  63485. this.unlocked = false;
  63486. this.isMP3supported = false;
  63487. this.isOGGsupported = false;
  63488. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63489. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63490. this.canUseWebAudio = true;
  63491. }
  63492. var audioElem = document.createElement('audio');
  63493. try {
  63494. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63495. this.isMP3supported = true;
  63496. }
  63497. }
  63498. catch (e) {
  63499. // protect error during capability check.
  63500. }
  63501. try {
  63502. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63503. this.isOGGsupported = true;
  63504. }
  63505. }
  63506. catch (e) {
  63507. // protect error during capability check.
  63508. }
  63509. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63510. this._unlockiOSaudio();
  63511. }
  63512. else {
  63513. this.unlocked = true;
  63514. }
  63515. }
  63516. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63517. get: function () {
  63518. if (!this._audioContextInitialized) {
  63519. this._initializeAudioContext();
  63520. }
  63521. return this._audioContext;
  63522. },
  63523. enumerable: true,
  63524. configurable: true
  63525. });
  63526. AudioEngine.prototype._unlockiOSaudio = function () {
  63527. var _this = this;
  63528. var unlockaudio = function () {
  63529. if (!_this.audioContext) {
  63530. return;
  63531. }
  63532. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63533. var source = _this.audioContext.createBufferSource();
  63534. source.buffer = buffer;
  63535. source.connect(_this.audioContext.destination);
  63536. source.start(0);
  63537. setTimeout(function () {
  63538. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  63539. _this.unlocked = true;
  63540. window.removeEventListener('touchend', unlockaudio, false);
  63541. if (_this.onAudioUnlocked) {
  63542. _this.onAudioUnlocked();
  63543. }
  63544. }
  63545. }, 0);
  63546. };
  63547. window.addEventListener('touchend', unlockaudio, false);
  63548. };
  63549. AudioEngine.prototype._initializeAudioContext = function () {
  63550. try {
  63551. if (this.canUseWebAudio) {
  63552. this._audioContext = new AudioContext();
  63553. // create a global volume gain node
  63554. this.masterGain = this._audioContext.createGain();
  63555. this.masterGain.gain.value = 1;
  63556. this.masterGain.connect(this._audioContext.destination);
  63557. this._audioContextInitialized = true;
  63558. }
  63559. }
  63560. catch (e) {
  63561. this.canUseWebAudio = false;
  63562. BABYLON.Tools.Error("Web Audio: " + e.message);
  63563. }
  63564. };
  63565. AudioEngine.prototype.dispose = function () {
  63566. if (this.canUseWebAudio && this._audioContextInitialized) {
  63567. if (this._connectedAnalyser && this._audioContext) {
  63568. this._connectedAnalyser.stopDebugCanvas();
  63569. this._connectedAnalyser.dispose();
  63570. this.masterGain.disconnect();
  63571. this.masterGain.connect(this._audioContext.destination);
  63572. this._connectedAnalyser = null;
  63573. }
  63574. this.masterGain.gain.value = 1;
  63575. }
  63576. this.WarnedWebAudioUnsupported = false;
  63577. };
  63578. AudioEngine.prototype.getGlobalVolume = function () {
  63579. if (this.canUseWebAudio && this._audioContextInitialized) {
  63580. return this.masterGain.gain.value;
  63581. }
  63582. else {
  63583. return -1;
  63584. }
  63585. };
  63586. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  63587. if (this.canUseWebAudio && this._audioContextInitialized) {
  63588. this.masterGain.gain.value = newVolume;
  63589. }
  63590. };
  63591. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  63592. if (this._connectedAnalyser) {
  63593. this._connectedAnalyser.stopDebugCanvas();
  63594. }
  63595. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  63596. this._connectedAnalyser = analyser;
  63597. this.masterGain.disconnect();
  63598. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  63599. }
  63600. };
  63601. return AudioEngine;
  63602. }());
  63603. BABYLON.AudioEngine = AudioEngine;
  63604. })(BABYLON || (BABYLON = {}));
  63605. //# sourceMappingURL=babylon.audioEngine.js.map
  63606. var BABYLON;
  63607. (function (BABYLON) {
  63608. var Sound = /** @class */ (function () {
  63609. /**
  63610. * Create a sound and attach it to a scene
  63611. * @param name Name of your sound
  63612. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  63613. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  63614. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  63615. */
  63616. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  63617. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  63618. var _this = this;
  63619. this.autoplay = false;
  63620. this.loop = false;
  63621. this.useCustomAttenuation = false;
  63622. this.spatialSound = false;
  63623. this.refDistance = 1;
  63624. this.rolloffFactor = 1;
  63625. this.maxDistance = 100;
  63626. this.distanceModel = "linear";
  63627. this._panningModel = "equalpower";
  63628. this._playbackRate = 1;
  63629. this._streaming = false;
  63630. this._startTime = 0;
  63631. this._startOffset = 0;
  63632. this._position = BABYLON.Vector3.Zero();
  63633. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  63634. this._volume = 1;
  63635. this._isReadyToPlay = false;
  63636. this.isPlaying = false;
  63637. this.isPaused = false;
  63638. this._isDirectional = false;
  63639. // Used if you'd like to create a directional sound.
  63640. // If not set, the sound will be omnidirectional
  63641. this._coneInnerAngle = 360;
  63642. this._coneOuterAngle = 360;
  63643. this._coneOuterGain = 0;
  63644. this._isOutputConnected = false;
  63645. this._urlType = "Unknown";
  63646. this.name = name;
  63647. this._scene = scene;
  63648. this._readyToPlayCallback = readyToPlayCallback;
  63649. // Default custom attenuation function is a linear attenuation
  63650. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  63651. if (currentDistance < maxDistance) {
  63652. return currentVolume * (1 - currentDistance / maxDistance);
  63653. }
  63654. else {
  63655. return 0;
  63656. }
  63657. };
  63658. if (options) {
  63659. this.autoplay = options.autoplay || false;
  63660. this.loop = options.loop || false;
  63661. // if volume === 0, we need another way to check this option
  63662. if (options.volume !== undefined) {
  63663. this._volume = options.volume;
  63664. }
  63665. this.spatialSound = options.spatialSound || false;
  63666. this.maxDistance = options.maxDistance || 100;
  63667. this.useCustomAttenuation = options.useCustomAttenuation || false;
  63668. this.rolloffFactor = options.rolloffFactor || 1;
  63669. this.refDistance = options.refDistance || 1;
  63670. this.distanceModel = options.distanceModel || "linear";
  63671. this._playbackRate = options.playbackRate || 1;
  63672. this._streaming = options.streaming || false;
  63673. }
  63674. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63675. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  63676. this._soundGain.gain.value = this._volume;
  63677. this._inputAudioNode = this._soundGain;
  63678. this._ouputAudioNode = this._soundGain;
  63679. if (this.spatialSound) {
  63680. this._createSpatialParameters();
  63681. }
  63682. this._scene.mainSoundTrack.AddSound(this);
  63683. var validParameter = true;
  63684. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  63685. if (urlOrArrayBuffer) {
  63686. try {
  63687. if (typeof (urlOrArrayBuffer) === "string") {
  63688. this._urlType = "String";
  63689. }
  63690. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  63691. this._urlType = "ArrayBuffer";
  63692. }
  63693. else if (urlOrArrayBuffer instanceof MediaStream) {
  63694. this._urlType = "MediaStream";
  63695. }
  63696. else if (Array.isArray(urlOrArrayBuffer)) {
  63697. this._urlType = "Array";
  63698. }
  63699. var urls = [];
  63700. var codecSupportedFound = false;
  63701. switch (this._urlType) {
  63702. case "MediaStream":
  63703. this._streaming = true;
  63704. this._isReadyToPlay = true;
  63705. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  63706. if (this.autoplay) {
  63707. this.play();
  63708. }
  63709. if (this._readyToPlayCallback) {
  63710. this._readyToPlayCallback();
  63711. }
  63712. break;
  63713. case "ArrayBuffer":
  63714. if (urlOrArrayBuffer.byteLength > 0) {
  63715. codecSupportedFound = true;
  63716. this._soundLoaded(urlOrArrayBuffer);
  63717. }
  63718. break;
  63719. case "String":
  63720. urls.push(urlOrArrayBuffer);
  63721. case "Array":
  63722. if (urls.length === 0)
  63723. urls = urlOrArrayBuffer;
  63724. // If we found a supported format, we load it immediately and stop the loop
  63725. for (var i = 0; i < urls.length; i++) {
  63726. var url = urls[i];
  63727. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  63728. codecSupportedFound = true;
  63729. }
  63730. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  63731. codecSupportedFound = true;
  63732. }
  63733. if (url.indexOf(".wav", url.length - 4) !== -1) {
  63734. codecSupportedFound = true;
  63735. }
  63736. if (url.indexOf("blob:") !== -1) {
  63737. codecSupportedFound = true;
  63738. }
  63739. if (codecSupportedFound) {
  63740. // Loading sound using XHR2
  63741. if (!this._streaming) {
  63742. this._scene._loadFile(url, function (data) {
  63743. _this._soundLoaded(data);
  63744. }, undefined, true, true, function (exception) {
  63745. if (exception) {
  63746. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  63747. }
  63748. BABYLON.Tools.Error("Sound creation aborted.");
  63749. _this._scene.mainSoundTrack.RemoveSound(_this);
  63750. });
  63751. }
  63752. // Streaming sound using HTML5 Audio tag
  63753. else {
  63754. this._htmlAudioElement = new Audio(url);
  63755. this._htmlAudioElement.controls = false;
  63756. this._htmlAudioElement.loop = this.loop;
  63757. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  63758. this._htmlAudioElement.preload = "auto";
  63759. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  63760. _this._isReadyToPlay = true;
  63761. if (_this.autoplay) {
  63762. _this.play();
  63763. }
  63764. if (_this._readyToPlayCallback) {
  63765. _this._readyToPlayCallback();
  63766. }
  63767. });
  63768. document.body.appendChild(this._htmlAudioElement);
  63769. }
  63770. break;
  63771. }
  63772. }
  63773. break;
  63774. default:
  63775. validParameter = false;
  63776. break;
  63777. }
  63778. if (!validParameter) {
  63779. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  63780. }
  63781. else {
  63782. if (!codecSupportedFound) {
  63783. this._isReadyToPlay = true;
  63784. // Simulating a ready to play event to avoid breaking code path
  63785. if (this._readyToPlayCallback) {
  63786. window.setTimeout(function () {
  63787. if (_this._readyToPlayCallback) {
  63788. _this._readyToPlayCallback();
  63789. }
  63790. }, 1000);
  63791. }
  63792. }
  63793. }
  63794. }
  63795. catch (ex) {
  63796. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  63797. this._scene.mainSoundTrack.RemoveSound(this);
  63798. }
  63799. }
  63800. }
  63801. else {
  63802. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  63803. this._scene.mainSoundTrack.AddSound(this);
  63804. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  63805. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  63806. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  63807. }
  63808. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  63809. if (this._readyToPlayCallback) {
  63810. window.setTimeout(function () {
  63811. if (_this._readyToPlayCallback) {
  63812. _this._readyToPlayCallback();
  63813. }
  63814. }, 1000);
  63815. }
  63816. }
  63817. }
  63818. Sound.prototype.dispose = function () {
  63819. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63820. if (this.isPlaying) {
  63821. this.stop();
  63822. }
  63823. this._isReadyToPlay = false;
  63824. if (this.soundTrackId === -1) {
  63825. this._scene.mainSoundTrack.RemoveSound(this);
  63826. }
  63827. else {
  63828. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  63829. }
  63830. if (this._soundGain) {
  63831. this._soundGain.disconnect();
  63832. this._soundGain = null;
  63833. }
  63834. if (this._soundPanner) {
  63835. this._soundPanner.disconnect();
  63836. this._soundPanner = null;
  63837. }
  63838. if (this._soundSource) {
  63839. this._soundSource.disconnect();
  63840. this._soundSource = null;
  63841. }
  63842. this._audioBuffer = null;
  63843. if (this._htmlAudioElement) {
  63844. this._htmlAudioElement.pause();
  63845. this._htmlAudioElement.src = "";
  63846. document.body.removeChild(this._htmlAudioElement);
  63847. }
  63848. if (this._streamingSource) {
  63849. this._streamingSource.disconnect();
  63850. }
  63851. if (this._connectedMesh && this._registerFunc) {
  63852. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63853. this._connectedMesh = null;
  63854. }
  63855. }
  63856. };
  63857. Sound.prototype.isReady = function () {
  63858. return this._isReadyToPlay;
  63859. };
  63860. Sound.prototype._soundLoaded = function (audioData) {
  63861. var _this = this;
  63862. if (!BABYLON.Engine.audioEngine.audioContext) {
  63863. return;
  63864. }
  63865. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  63866. _this._audioBuffer = buffer;
  63867. _this._isReadyToPlay = true;
  63868. if (_this.autoplay) {
  63869. _this.play();
  63870. }
  63871. if (_this._readyToPlayCallback) {
  63872. _this._readyToPlayCallback();
  63873. }
  63874. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  63875. };
  63876. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  63877. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63878. this._audioBuffer = audioBuffer;
  63879. this._isReadyToPlay = true;
  63880. }
  63881. };
  63882. Sound.prototype.updateOptions = function (options) {
  63883. if (options) {
  63884. this.loop = options.loop || this.loop;
  63885. this.maxDistance = options.maxDistance || this.maxDistance;
  63886. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  63887. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  63888. this.refDistance = options.refDistance || this.refDistance;
  63889. this.distanceModel = options.distanceModel || this.distanceModel;
  63890. this._playbackRate = options.playbackRate || this._playbackRate;
  63891. this._updateSpatialParameters();
  63892. if (this.isPlaying) {
  63893. if (this._streaming && this._htmlAudioElement) {
  63894. this._htmlAudioElement.playbackRate = this._playbackRate;
  63895. }
  63896. else {
  63897. if (this._soundSource) {
  63898. this._soundSource.playbackRate.value = this._playbackRate;
  63899. }
  63900. }
  63901. }
  63902. }
  63903. };
  63904. Sound.prototype._createSpatialParameters = function () {
  63905. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63906. if (this._scene.headphone) {
  63907. this._panningModel = "HRTF";
  63908. }
  63909. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  63910. this._updateSpatialParameters();
  63911. this._soundPanner.connect(this._ouputAudioNode);
  63912. this._inputAudioNode = this._soundPanner;
  63913. }
  63914. };
  63915. Sound.prototype._updateSpatialParameters = function () {
  63916. if (this.spatialSound && this._soundPanner) {
  63917. if (this.useCustomAttenuation) {
  63918. // Tricks to disable in a way embedded Web Audio attenuation
  63919. this._soundPanner.distanceModel = "linear";
  63920. this._soundPanner.maxDistance = Number.MAX_VALUE;
  63921. this._soundPanner.refDistance = 1;
  63922. this._soundPanner.rolloffFactor = 1;
  63923. this._soundPanner.panningModel = this._panningModel;
  63924. }
  63925. else {
  63926. this._soundPanner.distanceModel = this.distanceModel;
  63927. this._soundPanner.maxDistance = this.maxDistance;
  63928. this._soundPanner.refDistance = this.refDistance;
  63929. this._soundPanner.rolloffFactor = this.rolloffFactor;
  63930. this._soundPanner.panningModel = this._panningModel;
  63931. }
  63932. }
  63933. };
  63934. Sound.prototype.switchPanningModelToHRTF = function () {
  63935. this._panningModel = "HRTF";
  63936. this._switchPanningModel();
  63937. };
  63938. Sound.prototype.switchPanningModelToEqualPower = function () {
  63939. this._panningModel = "equalpower";
  63940. this._switchPanningModel();
  63941. };
  63942. Sound.prototype._switchPanningModel = function () {
  63943. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63944. this._soundPanner.panningModel = this._panningModel;
  63945. }
  63946. };
  63947. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  63948. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63949. if (this._isOutputConnected) {
  63950. this._ouputAudioNode.disconnect();
  63951. }
  63952. this._ouputAudioNode.connect(soundTrackAudioNode);
  63953. this._isOutputConnected = true;
  63954. }
  63955. };
  63956. /**
  63957. * Transform this sound into a directional source
  63958. * @param coneInnerAngle Size of the inner cone in degree
  63959. * @param coneOuterAngle Size of the outer cone in degree
  63960. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63961. */
  63962. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63963. if (coneOuterAngle < coneInnerAngle) {
  63964. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63965. return;
  63966. }
  63967. this._coneInnerAngle = coneInnerAngle;
  63968. this._coneOuterAngle = coneOuterAngle;
  63969. this._coneOuterGain = coneOuterGain;
  63970. this._isDirectional = true;
  63971. if (this.isPlaying && this.loop) {
  63972. this.stop();
  63973. this.play();
  63974. }
  63975. };
  63976. Sound.prototype.setPosition = function (newPosition) {
  63977. this._position = newPosition;
  63978. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63979. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63980. }
  63981. };
  63982. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63983. this._localDirection = newLocalDirection;
  63984. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63985. this._updateDirection();
  63986. }
  63987. };
  63988. Sound.prototype._updateDirection = function () {
  63989. if (!this._connectedMesh || !this._soundPanner) {
  63990. return;
  63991. }
  63992. var mat = this._connectedMesh.getWorldMatrix();
  63993. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63994. direction.normalize();
  63995. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63996. };
  63997. Sound.prototype.updateDistanceFromListener = function () {
  63998. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  63999. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64000. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64001. }
  64002. };
  64003. Sound.prototype.setAttenuationFunction = function (callback) {
  64004. this._customAttenuationFunction = callback;
  64005. };
  64006. /**
  64007. * Play the sound
  64008. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64009. * @param offset (optional) Start the sound setting it at a specific time
  64010. */
  64011. Sound.prototype.play = function (time, offset) {
  64012. var _this = this;
  64013. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  64014. try {
  64015. if (this._startOffset < 0) {
  64016. time = -this._startOffset;
  64017. this._startOffset = 0;
  64018. }
  64019. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64020. if (!this._soundSource || !this._streamingSource) {
  64021. if (this.spatialSound && this._soundPanner) {
  64022. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64023. if (this._isDirectional) {
  64024. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64025. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64026. this._soundPanner.coneOuterGain = this._coneOuterGain;
  64027. if (this._connectedMesh) {
  64028. this._updateDirection();
  64029. }
  64030. else {
  64031. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  64032. }
  64033. }
  64034. }
  64035. }
  64036. if (this._streaming) {
  64037. if (!this._streamingSource) {
  64038. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  64039. this._htmlAudioElement.onended = function () { _this._onended(); };
  64040. this._htmlAudioElement.playbackRate = this._playbackRate;
  64041. }
  64042. this._streamingSource.disconnect();
  64043. this._streamingSource.connect(this._inputAudioNode);
  64044. if (this._htmlAudioElement) {
  64045. this._htmlAudioElement.play();
  64046. }
  64047. }
  64048. else {
  64049. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  64050. this._soundSource.buffer = this._audioBuffer;
  64051. this._soundSource.connect(this._inputAudioNode);
  64052. this._soundSource.loop = this.loop;
  64053. this._soundSource.playbackRate.value = this._playbackRate;
  64054. this._soundSource.onended = function () { _this._onended(); };
  64055. if (this._soundSource.buffer) {
  64056. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  64057. }
  64058. }
  64059. this._startTime = startTime;
  64060. this.isPlaying = true;
  64061. this.isPaused = false;
  64062. }
  64063. catch (ex) {
  64064. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  64065. }
  64066. }
  64067. };
  64068. Sound.prototype._onended = function () {
  64069. this.isPlaying = false;
  64070. if (this.onended) {
  64071. this.onended();
  64072. }
  64073. };
  64074. /**
  64075. * Stop the sound
  64076. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  64077. */
  64078. Sound.prototype.stop = function (time) {
  64079. if (this.isPlaying) {
  64080. if (this._streaming) {
  64081. if (this._htmlAudioElement) {
  64082. this._htmlAudioElement.pause();
  64083. // Test needed for Firefox or it will generate an Invalid State Error
  64084. if (this._htmlAudioElement.currentTime > 0) {
  64085. this._htmlAudioElement.currentTime = 0;
  64086. }
  64087. }
  64088. else {
  64089. this._streamingSource.disconnect();
  64090. }
  64091. }
  64092. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  64093. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64094. this._soundSource.stop(stopTime);
  64095. this._soundSource.onended = function () { };
  64096. if (!this.isPaused) {
  64097. this._startOffset = 0;
  64098. }
  64099. }
  64100. this.isPlaying = false;
  64101. }
  64102. };
  64103. Sound.prototype.pause = function () {
  64104. if (this.isPlaying) {
  64105. this.isPaused = true;
  64106. if (this._streaming) {
  64107. if (this._htmlAudioElement) {
  64108. this._htmlAudioElement.pause();
  64109. }
  64110. else {
  64111. this._streamingSource.disconnect();
  64112. }
  64113. }
  64114. else if (BABYLON.Engine.audioEngine.audioContext) {
  64115. this.stop(0);
  64116. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  64117. }
  64118. }
  64119. };
  64120. Sound.prototype.setVolume = function (newVolume, time) {
  64121. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  64122. if (time && BABYLON.Engine.audioEngine.audioContext) {
  64123. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  64124. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  64125. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  64126. }
  64127. else {
  64128. this._soundGain.gain.value = newVolume;
  64129. }
  64130. }
  64131. this._volume = newVolume;
  64132. };
  64133. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  64134. this._playbackRate = newPlaybackRate;
  64135. if (this.isPlaying) {
  64136. if (this._streaming && this._htmlAudioElement) {
  64137. this._htmlAudioElement.playbackRate = this._playbackRate;
  64138. }
  64139. else if (this._soundSource) {
  64140. this._soundSource.playbackRate.value = this._playbackRate;
  64141. }
  64142. }
  64143. };
  64144. Sound.prototype.getVolume = function () {
  64145. return this._volume;
  64146. };
  64147. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  64148. var _this = this;
  64149. if (this._connectedMesh && this._registerFunc) {
  64150. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64151. this._registerFunc = null;
  64152. }
  64153. this._connectedMesh = meshToConnectTo;
  64154. if (!this.spatialSound) {
  64155. this.spatialSound = true;
  64156. this._createSpatialParameters();
  64157. if (this.isPlaying && this.loop) {
  64158. this.stop();
  64159. this.play();
  64160. }
  64161. }
  64162. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  64163. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  64164. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  64165. };
  64166. Sound.prototype.detachFromMesh = function () {
  64167. if (this._connectedMesh && this._registerFunc) {
  64168. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64169. this._registerFunc = null;
  64170. this._connectedMesh = null;
  64171. }
  64172. };
  64173. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  64174. if (!node.getBoundingInfo) {
  64175. return;
  64176. }
  64177. var mesh = node;
  64178. var boundingInfo = mesh.getBoundingInfo();
  64179. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  64180. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  64181. this._updateDirection();
  64182. }
  64183. };
  64184. Sound.prototype.clone = function () {
  64185. var _this = this;
  64186. if (!this._streaming) {
  64187. var setBufferAndRun = function () {
  64188. if (_this._isReadyToPlay) {
  64189. clonedSound._audioBuffer = _this.getAudioBuffer();
  64190. clonedSound._isReadyToPlay = true;
  64191. if (clonedSound.autoplay) {
  64192. clonedSound.play();
  64193. }
  64194. }
  64195. else {
  64196. window.setTimeout(setBufferAndRun, 300);
  64197. }
  64198. };
  64199. var currentOptions = {
  64200. autoplay: this.autoplay, loop: this.loop,
  64201. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  64202. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  64203. refDistance: this.refDistance, distanceModel: this.distanceModel
  64204. };
  64205. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  64206. if (this.useCustomAttenuation) {
  64207. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  64208. }
  64209. clonedSound.setPosition(this._position);
  64210. clonedSound.setPlaybackRate(this._playbackRate);
  64211. setBufferAndRun();
  64212. return clonedSound;
  64213. }
  64214. // Can't clone a streaming sound
  64215. else {
  64216. return null;
  64217. }
  64218. };
  64219. Sound.prototype.getAudioBuffer = function () {
  64220. return this._audioBuffer;
  64221. };
  64222. Sound.prototype.serialize = function () {
  64223. var serializationObject = {
  64224. name: this.name,
  64225. url: this.name,
  64226. autoplay: this.autoplay,
  64227. loop: this.loop,
  64228. volume: this._volume,
  64229. spatialSound: this.spatialSound,
  64230. maxDistance: this.maxDistance,
  64231. rolloffFactor: this.rolloffFactor,
  64232. refDistance: this.refDistance,
  64233. distanceModel: this.distanceModel,
  64234. playbackRate: this._playbackRate,
  64235. panningModel: this._panningModel,
  64236. soundTrackId: this.soundTrackId
  64237. };
  64238. if (this.spatialSound) {
  64239. if (this._connectedMesh)
  64240. serializationObject.connectedMeshId = this._connectedMesh.id;
  64241. serializationObject.position = this._position.asArray();
  64242. serializationObject.refDistance = this.refDistance;
  64243. serializationObject.distanceModel = this.distanceModel;
  64244. serializationObject.isDirectional = this._isDirectional;
  64245. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  64246. serializationObject.coneInnerAngle = this._coneInnerAngle;
  64247. serializationObject.coneOuterAngle = this._coneOuterAngle;
  64248. serializationObject.coneOuterGain = this._coneOuterGain;
  64249. }
  64250. return serializationObject;
  64251. };
  64252. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  64253. var soundName = parsedSound.name;
  64254. var soundUrl;
  64255. if (parsedSound.url) {
  64256. soundUrl = rootUrl + parsedSound.url;
  64257. }
  64258. else {
  64259. soundUrl = rootUrl + soundName;
  64260. }
  64261. var options = {
  64262. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  64263. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  64264. rolloffFactor: parsedSound.rolloffFactor,
  64265. refDistance: parsedSound.refDistance,
  64266. distanceModel: parsedSound.distanceModel,
  64267. playbackRate: parsedSound.playbackRate
  64268. };
  64269. var newSound;
  64270. if (!sourceSound) {
  64271. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  64272. scene._addPendingData(newSound);
  64273. }
  64274. else {
  64275. var setBufferAndRun = function () {
  64276. if (sourceSound._isReadyToPlay) {
  64277. newSound._audioBuffer = sourceSound.getAudioBuffer();
  64278. newSound._isReadyToPlay = true;
  64279. if (newSound.autoplay) {
  64280. newSound.play();
  64281. }
  64282. }
  64283. else {
  64284. window.setTimeout(setBufferAndRun, 300);
  64285. }
  64286. };
  64287. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  64288. setBufferAndRun();
  64289. }
  64290. if (parsedSound.position) {
  64291. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  64292. newSound.setPosition(soundPosition);
  64293. }
  64294. if (parsedSound.isDirectional) {
  64295. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  64296. if (parsedSound.localDirectionToMesh) {
  64297. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  64298. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  64299. }
  64300. }
  64301. if (parsedSound.connectedMeshId) {
  64302. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  64303. if (connectedMesh) {
  64304. newSound.attachToMesh(connectedMesh);
  64305. }
  64306. }
  64307. return newSound;
  64308. };
  64309. return Sound;
  64310. }());
  64311. BABYLON.Sound = Sound;
  64312. })(BABYLON || (BABYLON = {}));
  64313. //# sourceMappingURL=babylon.sound.js.map
  64314. var BABYLON;
  64315. (function (BABYLON) {
  64316. var SoundTrack = /** @class */ (function () {
  64317. function SoundTrack(scene, options) {
  64318. this.id = -1;
  64319. this._isMainTrack = false;
  64320. this._isInitialized = false;
  64321. this._scene = scene;
  64322. this.soundCollection = new Array();
  64323. this._options = options;
  64324. if (!this._isMainTrack) {
  64325. this._scene.soundTracks.push(this);
  64326. this.id = this._scene.soundTracks.length - 1;
  64327. }
  64328. }
  64329. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  64330. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64331. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  64332. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  64333. if (this._options) {
  64334. if (this._options.volume) {
  64335. this._outputAudioNode.gain.value = this._options.volume;
  64336. }
  64337. if (this._options.mainTrack) {
  64338. this._isMainTrack = this._options.mainTrack;
  64339. }
  64340. }
  64341. this._isInitialized = true;
  64342. }
  64343. };
  64344. SoundTrack.prototype.dispose = function () {
  64345. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  64346. if (this._connectedAnalyser) {
  64347. this._connectedAnalyser.stopDebugCanvas();
  64348. }
  64349. while (this.soundCollection.length) {
  64350. this.soundCollection[0].dispose();
  64351. }
  64352. if (this._outputAudioNode) {
  64353. this._outputAudioNode.disconnect();
  64354. }
  64355. this._outputAudioNode = null;
  64356. }
  64357. };
  64358. SoundTrack.prototype.AddSound = function (sound) {
  64359. if (!this._isInitialized) {
  64360. this._initializeSoundTrackAudioGraph();
  64361. }
  64362. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64363. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  64364. }
  64365. if (sound.soundTrackId) {
  64366. if (sound.soundTrackId === -1) {
  64367. this._scene.mainSoundTrack.RemoveSound(sound);
  64368. }
  64369. else {
  64370. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  64371. }
  64372. }
  64373. this.soundCollection.push(sound);
  64374. sound.soundTrackId = this.id;
  64375. };
  64376. SoundTrack.prototype.RemoveSound = function (sound) {
  64377. var index = this.soundCollection.indexOf(sound);
  64378. if (index !== -1) {
  64379. this.soundCollection.splice(index, 1);
  64380. }
  64381. };
  64382. SoundTrack.prototype.setVolume = function (newVolume) {
  64383. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64384. this._outputAudioNode.gain.value = newVolume;
  64385. }
  64386. };
  64387. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  64388. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64389. for (var i = 0; i < this.soundCollection.length; i++) {
  64390. this.soundCollection[i].switchPanningModelToHRTF();
  64391. }
  64392. }
  64393. };
  64394. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  64395. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64396. for (var i = 0; i < this.soundCollection.length; i++) {
  64397. this.soundCollection[i].switchPanningModelToEqualPower();
  64398. }
  64399. }
  64400. };
  64401. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64402. if (this._connectedAnalyser) {
  64403. this._connectedAnalyser.stopDebugCanvas();
  64404. }
  64405. this._connectedAnalyser = analyser;
  64406. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64407. this._outputAudioNode.disconnect();
  64408. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64409. }
  64410. };
  64411. return SoundTrack;
  64412. }());
  64413. BABYLON.SoundTrack = SoundTrack;
  64414. })(BABYLON || (BABYLON = {}));
  64415. //# sourceMappingURL=babylon.soundtrack.js.map
  64416. var BABYLON;
  64417. (function (BABYLON) {
  64418. /**
  64419. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64420. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64421. */
  64422. var Analyser = /** @class */ (function () {
  64423. /**
  64424. * Creates a new analyser
  64425. * @param scene defines hosting scene
  64426. */
  64427. function Analyser(scene) {
  64428. /**
  64429. * Gets or sets the smoothing
  64430. * @ignorenaming
  64431. */
  64432. this.SMOOTHING = 0.75;
  64433. /**
  64434. * Gets or sets the FFT table size
  64435. * @ignorenaming
  64436. */
  64437. this.FFT_SIZE = 512;
  64438. /**
  64439. * Gets or sets the bar graph amplitude
  64440. * @ignorenaming
  64441. */
  64442. this.BARGRAPHAMPLITUDE = 256;
  64443. /**
  64444. * Gets or sets the position of the debug canvas
  64445. * @ignorenaming
  64446. */
  64447. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64448. /**
  64449. * Gets or sets the debug canvas size
  64450. * @ignorenaming
  64451. */
  64452. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64453. this._scene = scene;
  64454. this._audioEngine = BABYLON.Engine.audioEngine;
  64455. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64456. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64457. this._webAudioAnalyser.minDecibels = -140;
  64458. this._webAudioAnalyser.maxDecibels = 0;
  64459. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64460. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64461. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64462. }
  64463. }
  64464. /**
  64465. * Get the number of data values you will have to play with for the visualization
  64466. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64467. * @returns a number
  64468. */
  64469. Analyser.prototype.getFrequencyBinCount = function () {
  64470. if (this._audioEngine.canUseWebAudio) {
  64471. return this._webAudioAnalyser.frequencyBinCount;
  64472. }
  64473. else {
  64474. return 0;
  64475. }
  64476. };
  64477. /**
  64478. * Gets the current frequency data as a byte array
  64479. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64480. * @returns a Uint8Array
  64481. */
  64482. Analyser.prototype.getByteFrequencyData = function () {
  64483. if (this._audioEngine.canUseWebAudio) {
  64484. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64485. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64486. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  64487. }
  64488. return this._byteFreqs;
  64489. };
  64490. /**
  64491. * Gets the current waveform as a byte array
  64492. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  64493. * @returns a Uint8Array
  64494. */
  64495. Analyser.prototype.getByteTimeDomainData = function () {
  64496. if (this._audioEngine.canUseWebAudio) {
  64497. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64498. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64499. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  64500. }
  64501. return this._byteTime;
  64502. };
  64503. /**
  64504. * Gets the current frequency data as a float array
  64505. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64506. * @returns a Float32Array
  64507. */
  64508. Analyser.prototype.getFloatFrequencyData = function () {
  64509. if (this._audioEngine.canUseWebAudio) {
  64510. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64511. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64512. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  64513. }
  64514. return this._floatFreqs;
  64515. };
  64516. /**
  64517. * Renders the debug canvas
  64518. */
  64519. Analyser.prototype.drawDebugCanvas = function () {
  64520. var _this = this;
  64521. if (this._audioEngine.canUseWebAudio) {
  64522. if (!this._debugCanvas) {
  64523. this._debugCanvas = document.createElement("canvas");
  64524. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  64525. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  64526. this._debugCanvas.style.position = "absolute";
  64527. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  64528. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  64529. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  64530. document.body.appendChild(this._debugCanvas);
  64531. this._registerFunc = function () {
  64532. _this.drawDebugCanvas();
  64533. };
  64534. this._scene.registerBeforeRender(this._registerFunc);
  64535. }
  64536. if (this._registerFunc && this._debugCanvasContext) {
  64537. var workingArray = this.getByteFrequencyData();
  64538. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  64539. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  64540. // Draw the frequency domain chart.
  64541. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  64542. var value = workingArray[i];
  64543. var percent = value / this.BARGRAPHAMPLITUDE;
  64544. var height = this.DEBUGCANVASSIZE.height * percent;
  64545. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  64546. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  64547. var hue = i / this.getFrequencyBinCount() * 360;
  64548. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  64549. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  64550. }
  64551. }
  64552. }
  64553. };
  64554. /**
  64555. * Stops rendering the debug canvas and removes it
  64556. */
  64557. Analyser.prototype.stopDebugCanvas = function () {
  64558. if (this._debugCanvas) {
  64559. if (this._registerFunc) {
  64560. this._scene.unregisterBeforeRender(this._registerFunc);
  64561. this._registerFunc = null;
  64562. }
  64563. document.body.removeChild(this._debugCanvas);
  64564. this._debugCanvas = null;
  64565. this._debugCanvasContext = null;
  64566. }
  64567. };
  64568. /**
  64569. * Connects two audio nodes
  64570. * @param inputAudioNode defines first node to connect
  64571. * @param outputAudioNode defines second node to connect
  64572. */
  64573. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  64574. if (this._audioEngine.canUseWebAudio) {
  64575. inputAudioNode.connect(this._webAudioAnalyser);
  64576. this._webAudioAnalyser.connect(outputAudioNode);
  64577. }
  64578. };
  64579. /**
  64580. * Releases all associated resources
  64581. */
  64582. Analyser.prototype.dispose = function () {
  64583. if (this._audioEngine.canUseWebAudio) {
  64584. this._webAudioAnalyser.disconnect();
  64585. }
  64586. };
  64587. return Analyser;
  64588. }());
  64589. BABYLON.Analyser = Analyser;
  64590. })(BABYLON || (BABYLON = {}));
  64591. //# sourceMappingURL=babylon.analyser.js.map
  64592. var BABYLON;
  64593. (function (BABYLON) {
  64594. var CubeTexture = /** @class */ (function (_super) {
  64595. __extends(CubeTexture, _super);
  64596. /**
  64597. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  64598. * as prefiltered data.
  64599. * @param rootUrl defines the url of the texture or the root name of the six images
  64600. * @param scene defines the scene the texture is attached to
  64601. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  64602. * @param noMipmap defines if mipmaps should be created or not
  64603. * @param files defines the six files to load for the different faces
  64604. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  64605. * @param onError defines a callback triggered in case of error during load
  64606. * @param format defines the internal format to use for the texture once loaded
  64607. * @param prefiltered defines whether or not the texture is created from prefiltered data
  64608. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  64609. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64610. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64611. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64612. * @return the cube texture
  64613. */
  64614. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  64615. if (extensions === void 0) { extensions = null; }
  64616. if (noMipmap === void 0) { noMipmap = false; }
  64617. if (files === void 0) { files = null; }
  64618. if (onLoad === void 0) { onLoad = null; }
  64619. if (onError === void 0) { onError = null; }
  64620. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64621. if (prefiltered === void 0) { prefiltered = false; }
  64622. if (forcedExtension === void 0) { forcedExtension = null; }
  64623. if (createPolynomials === void 0) { createPolynomials = false; }
  64624. if (lodScale === void 0) { lodScale = 0.8; }
  64625. if (lodOffset === void 0) { lodOffset = 0; }
  64626. var _this = _super.call(this, scene) || this;
  64627. /**
  64628. * Gets or sets the center of the bounding box associated with the cube texture
  64629. * It must define where the camera used to render the texture was set
  64630. */
  64631. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64632. _this._rotationY = 0;
  64633. /** @hidden */
  64634. _this._prefiltered = false;
  64635. _this.name = rootUrl;
  64636. _this.url = rootUrl;
  64637. _this._noMipmap = noMipmap;
  64638. _this.hasAlpha = false;
  64639. _this._format = format;
  64640. _this.isCube = true;
  64641. _this._textureMatrix = BABYLON.Matrix.Identity();
  64642. _this._createPolynomials = createPolynomials;
  64643. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64644. if (!rootUrl && !files) {
  64645. return _this;
  64646. }
  64647. var lastDot = rootUrl.lastIndexOf(".");
  64648. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  64649. var isDDS = (extension === ".dds");
  64650. var isEnv = (extension === ".env");
  64651. if (isEnv) {
  64652. _this.gammaSpace = false;
  64653. _this._prefiltered = false;
  64654. }
  64655. else {
  64656. _this._prefiltered = prefiltered;
  64657. if (prefiltered) {
  64658. _this.gammaSpace = false;
  64659. }
  64660. }
  64661. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  64662. if (!files) {
  64663. if (!isEnv && !isDDS && !extensions) {
  64664. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  64665. }
  64666. files = [];
  64667. if (extensions) {
  64668. for (var index = 0; index < extensions.length; index++) {
  64669. files.push(rootUrl + extensions[index]);
  64670. }
  64671. }
  64672. }
  64673. _this._files = files;
  64674. if (!_this._texture) {
  64675. if (!scene.useDelayedTextureLoading) {
  64676. if (prefiltered) {
  64677. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  64678. }
  64679. else {
  64680. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  64681. }
  64682. }
  64683. else {
  64684. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64685. }
  64686. }
  64687. else if (onLoad) {
  64688. if (_this._texture.isReady) {
  64689. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  64690. }
  64691. else {
  64692. _this._texture.onLoadedObservable.add(onLoad);
  64693. }
  64694. }
  64695. return _this;
  64696. }
  64697. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  64698. get: function () {
  64699. return this._boundingBoxSize;
  64700. },
  64701. /**
  64702. * Gets or sets the size of the bounding box associated with the cube texture
  64703. * When defined, the cubemap will switch to local mode
  64704. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64705. * @example https://www.babylonjs-playground.com/#RNASML
  64706. */
  64707. set: function (value) {
  64708. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64709. return;
  64710. }
  64711. this._boundingBoxSize = value;
  64712. var scene = this.getScene();
  64713. if (scene) {
  64714. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64715. }
  64716. },
  64717. enumerable: true,
  64718. configurable: true
  64719. });
  64720. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  64721. /**
  64722. * Gets texture matrix rotation angle around Y axis radians.
  64723. */
  64724. get: function () {
  64725. return this._rotationY;
  64726. },
  64727. /**
  64728. * Sets texture matrix rotation angle around Y axis in radians.
  64729. */
  64730. set: function (value) {
  64731. this._rotationY = value;
  64732. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  64733. },
  64734. enumerable: true,
  64735. configurable: true
  64736. });
  64737. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  64738. var rootUrlKey = "";
  64739. files.forEach(function (url) { return rootUrlKey += url; });
  64740. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  64741. };
  64742. /**
  64743. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  64744. * @param url defines the url of the prefiltered texture
  64745. * @param scene defines the scene the texture is attached to
  64746. * @param forcedExtension defines the extension of the file if different from the url
  64747. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64748. * @return the prefiltered texture
  64749. */
  64750. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  64751. if (forcedExtension === void 0) { forcedExtension = null; }
  64752. if (createPolynomials === void 0) { createPolynomials = true; }
  64753. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  64754. };
  64755. // Methods
  64756. CubeTexture.prototype.delayLoad = function () {
  64757. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64758. return;
  64759. }
  64760. var scene = this.getScene();
  64761. if (!scene) {
  64762. return;
  64763. }
  64764. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64765. this._texture = this._getFromCache(this.url, this._noMipmap);
  64766. if (!this._texture) {
  64767. if (this._prefiltered) {
  64768. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  64769. }
  64770. else {
  64771. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  64772. }
  64773. }
  64774. };
  64775. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  64776. return this._textureMatrix;
  64777. };
  64778. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64779. this._textureMatrix = value;
  64780. };
  64781. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64782. var texture = BABYLON.SerializationHelper.Parse(function () {
  64783. var prefiltered = false;
  64784. if (parsedTexture.prefiltered) {
  64785. prefiltered = parsedTexture.prefiltered;
  64786. }
  64787. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  64788. }, parsedTexture, scene);
  64789. // Local Cubemaps
  64790. if (parsedTexture.boundingBoxPosition) {
  64791. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  64792. }
  64793. if (parsedTexture.boundingBoxSize) {
  64794. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  64795. }
  64796. // Animations
  64797. if (parsedTexture.animations) {
  64798. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  64799. var parsedAnimation = parsedTexture.animations[animationIndex];
  64800. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  64801. }
  64802. }
  64803. return texture;
  64804. };
  64805. CubeTexture.prototype.clone = function () {
  64806. var _this = this;
  64807. return BABYLON.SerializationHelper.Clone(function () {
  64808. var scene = _this.getScene();
  64809. if (!scene) {
  64810. return _this;
  64811. }
  64812. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  64813. }, this);
  64814. };
  64815. __decorate([
  64816. BABYLON.serialize("rotationY")
  64817. ], CubeTexture.prototype, "_rotationY", void 0);
  64818. return CubeTexture;
  64819. }(BABYLON.BaseTexture));
  64820. BABYLON.CubeTexture = CubeTexture;
  64821. })(BABYLON || (BABYLON = {}));
  64822. //# sourceMappingURL=babylon.cubeTexture.js.map
  64823. var BABYLON;
  64824. (function (BABYLON) {
  64825. /**
  64826. * Raw cube texture where the raw buffers are passed in
  64827. */
  64828. var RawCubeTexture = /** @class */ (function (_super) {
  64829. __extends(RawCubeTexture, _super);
  64830. /**
  64831. * Creates a cube texture where the raw buffers are passed in.
  64832. * @param scene defines the scene the texture is attached to
  64833. * @param data defines the array of data to use to create each face
  64834. * @param size defines the size of the textures
  64835. * @param format defines the format of the data
  64836. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  64837. * @param generateMipMaps defines if the engine should generate the mip levels
  64838. * @param invertY defines if data must be stored with Y axis inverted
  64839. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  64840. * @param compression defines the compression used (null by default)
  64841. */
  64842. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  64843. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64844. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64845. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64846. if (invertY === void 0) { invertY = false; }
  64847. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64848. if (compression === void 0) { compression = null; }
  64849. var _this = _super.call(this, "", scene) || this;
  64850. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  64851. return _this;
  64852. }
  64853. /**
  64854. * Updates the raw cube texture.
  64855. * @param data defines the data to store
  64856. * @param format defines the data format
  64857. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  64858. * @param invertY defines if data must be stored with Y axis inverted
  64859. * @param compression defines the compression used (null by default)
  64860. * @param level defines which level of the texture to update
  64861. */
  64862. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  64863. if (compression === void 0) { compression = null; }
  64864. if (level === void 0) { level = 0; }
  64865. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  64866. };
  64867. /**
  64868. * Updates a raw cube texture with RGBD encoded data.
  64869. * @param data defines the array of data [mipmap][face] to use to create each face
  64870. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  64871. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64872. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64873. * @returns a promsie that resolves when the operation is complete
  64874. */
  64875. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  64876. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  64877. if (lodScale === void 0) { lodScale = 0.8; }
  64878. if (lodOffset === void 0) { lodOffset = 0; }
  64879. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  64880. };
  64881. /**
  64882. * Clones the raw cube texture.
  64883. * @return a new cube texture
  64884. */
  64885. RawCubeTexture.prototype.clone = function () {
  64886. var _this = this;
  64887. return BABYLON.SerializationHelper.Clone(function () {
  64888. var scene = _this.getScene();
  64889. var internalTexture = _this._texture;
  64890. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  64891. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  64892. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  64893. }
  64894. return texture;
  64895. }, this);
  64896. };
  64897. /** @hidden */
  64898. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  64899. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  64900. internalTexture._bufferViewArrayArray = data;
  64901. internalTexture._lodGenerationScale = lodScale;
  64902. internalTexture._lodGenerationOffset = lodOffset;
  64903. internalTexture._sphericalPolynomial = sphericalPolynomial;
  64904. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  64905. internalTexture.isReady = true;
  64906. });
  64907. };
  64908. return RawCubeTexture;
  64909. }(BABYLON.CubeTexture));
  64910. BABYLON.RawCubeTexture = RawCubeTexture;
  64911. })(BABYLON || (BABYLON = {}));
  64912. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  64913. var BABYLON;
  64914. (function (BABYLON) {
  64915. var RenderTargetTexture = /** @class */ (function (_super) {
  64916. __extends(RenderTargetTexture, _super);
  64917. /**
  64918. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  64919. * or used a shadow, depth texture...
  64920. * @param name The friendly name of the texture
  64921. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  64922. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  64923. * @param generateMipMaps True if mip maps need to be generated after render.
  64924. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  64925. * @param type The type of the buffer in the RTT (int, half float, float...)
  64926. * @param isCube True if a cube texture needs to be created
  64927. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  64928. * @param generateDepthBuffer True to generate a depth buffer
  64929. * @param generateStencilBuffer True to generate a stencil buffer
  64930. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  64931. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  64932. */
  64933. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  64934. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  64935. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64936. if (isCube === void 0) { isCube = false; }
  64937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64938. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64939. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  64940. if (isMulti === void 0) { isMulti = false; }
  64941. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64942. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64943. _this.isCube = isCube;
  64944. /**
  64945. * Use this list to define the list of mesh you want to render.
  64946. */
  64947. _this.renderList = new Array();
  64948. _this.renderParticles = true;
  64949. _this.renderSprites = false;
  64950. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  64951. _this.ignoreCameraViewport = false;
  64952. // Events
  64953. /**
  64954. * An event triggered when the texture is unbind.
  64955. */
  64956. _this.onBeforeBindObservable = new BABYLON.Observable();
  64957. /**
  64958. * An event triggered when the texture is unbind.
  64959. */
  64960. _this.onAfterUnbindObservable = new BABYLON.Observable();
  64961. /**
  64962. * An event triggered before rendering the texture
  64963. */
  64964. _this.onBeforeRenderObservable = new BABYLON.Observable();
  64965. /**
  64966. * An event triggered after rendering the texture
  64967. */
  64968. _this.onAfterRenderObservable = new BABYLON.Observable();
  64969. /**
  64970. * An event triggered after the texture clear
  64971. */
  64972. _this.onClearObservable = new BABYLON.Observable();
  64973. _this._currentRefreshId = -1;
  64974. _this._refreshRate = 1;
  64975. _this._samples = 1;
  64976. /**
  64977. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  64978. * It must define where the camera used to render the texture is set
  64979. */
  64980. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64981. scene = _this.getScene();
  64982. if (!scene) {
  64983. return _this;
  64984. }
  64985. _this._engine = scene.getEngine();
  64986. _this.name = name;
  64987. _this.isRenderTarget = true;
  64988. _this._initialSizeParameter = size;
  64989. _this._processSizeParameter(size);
  64990. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  64991. });
  64992. _this._generateMipMaps = generateMipMaps ? true : false;
  64993. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  64994. // Rendering groups
  64995. _this._renderingManager = new BABYLON.RenderingManager(scene);
  64996. _this._renderingManager._useSceneAutoClearSetup = true;
  64997. if (isMulti) {
  64998. return _this;
  64999. }
  65000. _this._renderTargetOptions = {
  65001. generateMipMaps: generateMipMaps,
  65002. type: type,
  65003. format: format,
  65004. samplingMode: samplingMode,
  65005. generateDepthBuffer: generateDepthBuffer,
  65006. generateStencilBuffer: generateStencilBuffer
  65007. };
  65008. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  65009. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65010. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65011. }
  65012. if (isCube) {
  65013. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  65014. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  65015. _this._textureMatrix = BABYLON.Matrix.Identity();
  65016. }
  65017. else {
  65018. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  65019. }
  65020. return _this;
  65021. }
  65022. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  65023. get: function () {
  65024. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  65025. },
  65026. enumerable: true,
  65027. configurable: true
  65028. });
  65029. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  65030. get: function () {
  65031. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  65032. },
  65033. enumerable: true,
  65034. configurable: true
  65035. });
  65036. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  65037. get: function () {
  65038. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  65039. },
  65040. enumerable: true,
  65041. configurable: true
  65042. });
  65043. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  65044. set: function (callback) {
  65045. if (this._onAfterUnbindObserver) {
  65046. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  65047. }
  65048. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  65049. },
  65050. enumerable: true,
  65051. configurable: true
  65052. });
  65053. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  65054. set: function (callback) {
  65055. if (this._onBeforeRenderObserver) {
  65056. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65057. }
  65058. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65059. },
  65060. enumerable: true,
  65061. configurable: true
  65062. });
  65063. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  65064. set: function (callback) {
  65065. if (this._onAfterRenderObserver) {
  65066. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65067. }
  65068. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65069. },
  65070. enumerable: true,
  65071. configurable: true
  65072. });
  65073. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  65074. set: function (callback) {
  65075. if (this._onClearObserver) {
  65076. this.onClearObservable.remove(this._onClearObserver);
  65077. }
  65078. this._onClearObserver = this.onClearObservable.add(callback);
  65079. },
  65080. enumerable: true,
  65081. configurable: true
  65082. });
  65083. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  65084. get: function () {
  65085. return this._renderTargetOptions;
  65086. },
  65087. enumerable: true,
  65088. configurable: true
  65089. });
  65090. RenderTargetTexture.prototype._onRatioRescale = function () {
  65091. if (this._sizeRatio) {
  65092. this.resize(this._initialSizeParameter);
  65093. }
  65094. };
  65095. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  65096. get: function () {
  65097. return this._boundingBoxSize;
  65098. },
  65099. /**
  65100. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  65101. * When defined, the cubemap will switch to local mode
  65102. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65103. * @example https://www.babylonjs-playground.com/#RNASML
  65104. */
  65105. set: function (value) {
  65106. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65107. return;
  65108. }
  65109. this._boundingBoxSize = value;
  65110. var scene = this.getScene();
  65111. if (scene) {
  65112. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65113. }
  65114. },
  65115. enumerable: true,
  65116. configurable: true
  65117. });
  65118. /**
  65119. * Creates a depth stencil texture.
  65120. * This is only available in WebGL 2 or with the depth texture extension available.
  65121. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  65122. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  65123. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  65124. */
  65125. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  65126. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  65127. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  65128. if (generateStencil === void 0) { generateStencil = false; }
  65129. if (!this.getScene()) {
  65130. return;
  65131. }
  65132. var engine = this.getScene().getEngine();
  65133. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  65134. bilinearFiltering: bilinearFiltering,
  65135. comparisonFunction: comparisonFunction,
  65136. generateStencil: generateStencil,
  65137. isCube: this.isCube
  65138. });
  65139. engine.setFrameBufferDepthStencilTexture(this);
  65140. };
  65141. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  65142. if (size.ratio) {
  65143. this._sizeRatio = size.ratio;
  65144. this._size = {
  65145. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  65146. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  65147. };
  65148. }
  65149. else {
  65150. this._size = size;
  65151. }
  65152. };
  65153. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  65154. get: function () {
  65155. return this._samples;
  65156. },
  65157. set: function (value) {
  65158. if (this._samples === value) {
  65159. return;
  65160. }
  65161. var scene = this.getScene();
  65162. if (!scene) {
  65163. return;
  65164. }
  65165. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  65166. },
  65167. enumerable: true,
  65168. configurable: true
  65169. });
  65170. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  65171. this._currentRefreshId = -1;
  65172. };
  65173. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  65174. get: function () {
  65175. return this._refreshRate;
  65176. },
  65177. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65178. set: function (value) {
  65179. this._refreshRate = value;
  65180. this.resetRefreshCounter();
  65181. },
  65182. enumerable: true,
  65183. configurable: true
  65184. });
  65185. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  65186. if (!this._postProcessManager) {
  65187. var scene = this.getScene();
  65188. if (!scene) {
  65189. return;
  65190. }
  65191. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  65192. this._postProcesses = new Array();
  65193. }
  65194. this._postProcesses.push(postProcess);
  65195. this._postProcesses[0].autoClear = false;
  65196. };
  65197. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  65198. if (!this._postProcesses) {
  65199. return;
  65200. }
  65201. if (dispose) {
  65202. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  65203. var postProcess = _a[_i];
  65204. postProcess.dispose();
  65205. }
  65206. }
  65207. this._postProcesses = [];
  65208. };
  65209. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  65210. if (!this._postProcesses) {
  65211. return;
  65212. }
  65213. var index = this._postProcesses.indexOf(postProcess);
  65214. if (index === -1) {
  65215. return;
  65216. }
  65217. this._postProcesses.splice(index, 1);
  65218. if (this._postProcesses.length > 0) {
  65219. this._postProcesses[0].autoClear = false;
  65220. }
  65221. };
  65222. RenderTargetTexture.prototype._shouldRender = function () {
  65223. if (this._currentRefreshId === -1) { // At least render once
  65224. this._currentRefreshId = 1;
  65225. return true;
  65226. }
  65227. if (this.refreshRate === this._currentRefreshId) {
  65228. this._currentRefreshId = 1;
  65229. return true;
  65230. }
  65231. this._currentRefreshId++;
  65232. return false;
  65233. };
  65234. RenderTargetTexture.prototype.getRenderSize = function () {
  65235. if (this._size.width) {
  65236. return this._size.width;
  65237. }
  65238. return this._size;
  65239. };
  65240. RenderTargetTexture.prototype.getRenderWidth = function () {
  65241. if (this._size.width) {
  65242. return this._size.width;
  65243. }
  65244. return this._size;
  65245. };
  65246. RenderTargetTexture.prototype.getRenderHeight = function () {
  65247. if (this._size.width) {
  65248. return this._size.height;
  65249. }
  65250. return this._size;
  65251. };
  65252. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  65253. get: function () {
  65254. return true;
  65255. },
  65256. enumerable: true,
  65257. configurable: true
  65258. });
  65259. RenderTargetTexture.prototype.scale = function (ratio) {
  65260. var newSize = this.getRenderSize() * ratio;
  65261. this.resize(newSize);
  65262. };
  65263. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  65264. if (this.isCube) {
  65265. return this._textureMatrix;
  65266. }
  65267. return _super.prototype.getReflectionTextureMatrix.call(this);
  65268. };
  65269. RenderTargetTexture.prototype.resize = function (size) {
  65270. this.releaseInternalTexture();
  65271. var scene = this.getScene();
  65272. if (!scene) {
  65273. return;
  65274. }
  65275. this._processSizeParameter(size);
  65276. if (this.isCube) {
  65277. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  65278. }
  65279. else {
  65280. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  65281. }
  65282. };
  65283. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  65284. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  65285. if (dumpForDebug === void 0) { dumpForDebug = false; }
  65286. var scene = this.getScene();
  65287. if (!scene) {
  65288. return;
  65289. }
  65290. var engine = scene.getEngine();
  65291. if (this.useCameraPostProcesses !== undefined) {
  65292. useCameraPostProcess = this.useCameraPostProcesses;
  65293. }
  65294. if (this._waitingRenderList) {
  65295. this.renderList = [];
  65296. for (var index = 0; index < this._waitingRenderList.length; index++) {
  65297. var id = this._waitingRenderList[index];
  65298. var mesh_1 = scene.getMeshByID(id);
  65299. if (mesh_1) {
  65300. this.renderList.push(mesh_1);
  65301. }
  65302. }
  65303. delete this._waitingRenderList;
  65304. }
  65305. // Is predicate defined?
  65306. if (this.renderListPredicate) {
  65307. if (this.renderList) {
  65308. this.renderList.splice(0); // Clear previous renderList
  65309. }
  65310. else {
  65311. this.renderList = [];
  65312. }
  65313. var scene = this.getScene();
  65314. if (!scene) {
  65315. return;
  65316. }
  65317. var sceneMeshes = scene.meshes;
  65318. for (var index = 0; index < sceneMeshes.length; index++) {
  65319. var mesh = sceneMeshes[index];
  65320. if (this.renderListPredicate(mesh)) {
  65321. this.renderList.push(mesh);
  65322. }
  65323. }
  65324. }
  65325. this.onBeforeBindObservable.notifyObservers(this);
  65326. // Set custom projection.
  65327. // Needs to be before binding to prevent changing the aspect ratio.
  65328. var camera;
  65329. if (this.activeCamera) {
  65330. camera = this.activeCamera;
  65331. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65332. if (this.activeCamera !== scene.activeCamera) {
  65333. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  65334. }
  65335. }
  65336. else {
  65337. camera = scene.activeCamera;
  65338. if (camera) {
  65339. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65340. }
  65341. }
  65342. // Prepare renderingManager
  65343. this._renderingManager.reset();
  65344. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  65345. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  65346. var sceneRenderId = scene.getRenderId();
  65347. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  65348. var mesh = currentRenderList[meshIndex];
  65349. if (mesh) {
  65350. if (!mesh.isReady(this.refreshRate === 0)) {
  65351. this.resetRefreshCounter();
  65352. continue;
  65353. }
  65354. mesh._preActivateForIntermediateRendering(sceneRenderId);
  65355. var isMasked = void 0;
  65356. if (!this.renderList && camera) {
  65357. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  65358. }
  65359. else {
  65360. isMasked = false;
  65361. }
  65362. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  65363. mesh._activate(sceneRenderId);
  65364. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  65365. var subMesh = mesh.subMeshes[subIndex];
  65366. scene._activeIndices.addCount(subMesh.indexCount, false);
  65367. this._renderingManager.dispatch(subMesh, mesh);
  65368. }
  65369. }
  65370. }
  65371. }
  65372. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  65373. var particleSystem = scene.particleSystems[particleIndex];
  65374. var emitter = particleSystem.emitter;
  65375. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  65376. continue;
  65377. }
  65378. if (currentRenderList.indexOf(emitter) >= 0) {
  65379. this._renderingManager.dispatchParticles(particleSystem);
  65380. }
  65381. }
  65382. if (this.isCube) {
  65383. for (var face = 0; face < 6; face++) {
  65384. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65385. scene.incrementRenderId();
  65386. scene.resetCachedMaterial();
  65387. }
  65388. }
  65389. else {
  65390. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65391. }
  65392. this.onAfterUnbindObservable.notifyObservers(this);
  65393. if (scene.activeCamera) {
  65394. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  65395. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  65396. }
  65397. engine.setViewport(scene.activeCamera.viewport);
  65398. }
  65399. scene.resetCachedMaterial();
  65400. };
  65401. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  65402. var minimum = 128;
  65403. var x = renderDimension * scale;
  65404. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  65405. // Ensure we don't exceed the render dimension (while staying POT)
  65406. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  65407. };
  65408. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65409. var _this = this;
  65410. if (!this._texture) {
  65411. return;
  65412. }
  65413. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  65414. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65415. });
  65416. };
  65417. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  65418. var scene = this.getScene();
  65419. if (!scene) {
  65420. return;
  65421. }
  65422. var engine = scene.getEngine();
  65423. if (!this._texture) {
  65424. return;
  65425. }
  65426. // Bind
  65427. if (this._postProcessManager) {
  65428. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  65429. }
  65430. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  65431. if (this._texture) {
  65432. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  65433. }
  65434. }
  65435. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  65436. // Clear
  65437. if (this.onClearObservable.hasObservers()) {
  65438. this.onClearObservable.notifyObservers(engine);
  65439. }
  65440. else {
  65441. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  65442. }
  65443. if (!this._doNotChangeAspectRatio) {
  65444. scene.updateTransformMatrix(true);
  65445. }
  65446. // Render
  65447. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  65448. if (this._postProcessManager) {
  65449. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  65450. }
  65451. else if (useCameraPostProcess) {
  65452. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  65453. }
  65454. if (!this._doNotChangeAspectRatio) {
  65455. scene.updateTransformMatrix(true);
  65456. }
  65457. // Dump ?
  65458. if (dumpForDebug) {
  65459. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  65460. }
  65461. // Unbind
  65462. if (!this.isCube || faceIndex === 5) {
  65463. if (this.isCube) {
  65464. if (faceIndex === 5) {
  65465. engine.generateMipMapsForCubemap(this._texture);
  65466. }
  65467. }
  65468. this.unbindFrameBuffer(engine, faceIndex);
  65469. }
  65470. else {
  65471. this.onAfterRenderObservable.notifyObservers(faceIndex);
  65472. }
  65473. };
  65474. /**
  65475. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  65476. * This allowed control for front to back rendering or reversly depending of the special needs.
  65477. *
  65478. * @param renderingGroupId The rendering group id corresponding to its index
  65479. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  65480. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  65481. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  65482. */
  65483. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  65484. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  65485. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  65486. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  65487. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  65488. };
  65489. /**
  65490. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  65491. *
  65492. * @param renderingGroupId The rendering group id corresponding to its index
  65493. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  65494. */
  65495. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  65496. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  65497. this._renderingManager._useSceneAutoClearSetup = false;
  65498. };
  65499. RenderTargetTexture.prototype.clone = function () {
  65500. var textureSize = this.getSize();
  65501. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  65502. // Base texture
  65503. newTexture.hasAlpha = this.hasAlpha;
  65504. newTexture.level = this.level;
  65505. // RenderTarget Texture
  65506. newTexture.coordinatesMode = this.coordinatesMode;
  65507. if (this.renderList) {
  65508. newTexture.renderList = this.renderList.slice(0);
  65509. }
  65510. return newTexture;
  65511. };
  65512. RenderTargetTexture.prototype.serialize = function () {
  65513. if (!this.name) {
  65514. return null;
  65515. }
  65516. var serializationObject = _super.prototype.serialize.call(this);
  65517. serializationObject.renderTargetSize = this.getRenderSize();
  65518. serializationObject.renderList = [];
  65519. if (this.renderList) {
  65520. for (var index = 0; index < this.renderList.length; index++) {
  65521. serializationObject.renderList.push(this.renderList[index].id);
  65522. }
  65523. }
  65524. return serializationObject;
  65525. };
  65526. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  65527. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  65528. var objBuffer = this.getInternalTexture();
  65529. var scene = this.getScene();
  65530. if (objBuffer && scene) {
  65531. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  65532. }
  65533. };
  65534. RenderTargetTexture.prototype.dispose = function () {
  65535. if (this._postProcessManager) {
  65536. this._postProcessManager.dispose();
  65537. this._postProcessManager = null;
  65538. }
  65539. this.clearPostProcesses(true);
  65540. if (this._resizeObserver) {
  65541. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  65542. this._resizeObserver = null;
  65543. }
  65544. this.renderList = null;
  65545. // Remove from custom render targets
  65546. var scene = this.getScene();
  65547. if (!scene) {
  65548. return;
  65549. }
  65550. var index = scene.customRenderTargets.indexOf(this);
  65551. if (index >= 0) {
  65552. scene.customRenderTargets.splice(index, 1);
  65553. }
  65554. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  65555. var camera = _a[_i];
  65556. index = camera.customRenderTargets.indexOf(this);
  65557. if (index >= 0) {
  65558. camera.customRenderTargets.splice(index, 1);
  65559. }
  65560. }
  65561. _super.prototype.dispose.call(this);
  65562. };
  65563. RenderTargetTexture.prototype._rebuild = function () {
  65564. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65565. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65566. }
  65567. if (this._postProcessManager) {
  65568. this._postProcessManager._rebuild();
  65569. }
  65570. };
  65571. /**
  65572. * Clear the info related to rendering groups preventing retention point in material dispose.
  65573. */
  65574. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  65575. if (this._renderingManager) {
  65576. this._renderingManager.freeRenderingGroups();
  65577. }
  65578. };
  65579. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  65580. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  65581. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  65582. return RenderTargetTexture;
  65583. }(BABYLON.Texture));
  65584. BABYLON.RenderTargetTexture = RenderTargetTexture;
  65585. })(BABYLON || (BABYLON = {}));
  65586. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  65587. var BABYLON;
  65588. (function (BABYLON) {
  65589. ;
  65590. var MultiRenderTarget = /** @class */ (function (_super) {
  65591. __extends(MultiRenderTarget, _super);
  65592. function MultiRenderTarget(name, size, count, scene, options) {
  65593. var _this = this;
  65594. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  65595. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  65596. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  65597. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  65598. _this._engine = scene.getEngine();
  65599. if (!_this.isSupported) {
  65600. _this.dispose();
  65601. return;
  65602. }
  65603. var types = [];
  65604. var samplingModes = [];
  65605. for (var i = 0; i < count; i++) {
  65606. if (options && options.types && options.types[i] !== undefined) {
  65607. types.push(options.types[i]);
  65608. }
  65609. else {
  65610. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65611. }
  65612. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  65613. samplingModes.push(options.samplingModes[i]);
  65614. }
  65615. else {
  65616. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65617. }
  65618. }
  65619. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  65620. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  65621. _this._size = size;
  65622. _this._multiRenderTargetOptions = {
  65623. samplingModes: samplingModes,
  65624. generateMipMaps: generateMipMaps,
  65625. generateDepthBuffer: generateDepthBuffer,
  65626. generateStencilBuffer: generateStencilBuffer,
  65627. generateDepthTexture: generateDepthTexture,
  65628. types: types,
  65629. textureCount: count
  65630. };
  65631. _this._createInternalTextures();
  65632. _this._createTextures();
  65633. return _this;
  65634. }
  65635. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  65636. get: function () {
  65637. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  65638. },
  65639. enumerable: true,
  65640. configurable: true
  65641. });
  65642. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  65643. get: function () {
  65644. return this._textures;
  65645. },
  65646. enumerable: true,
  65647. configurable: true
  65648. });
  65649. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  65650. get: function () {
  65651. return this._textures[this._textures.length - 1];
  65652. },
  65653. enumerable: true,
  65654. configurable: true
  65655. });
  65656. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  65657. set: function (wrap) {
  65658. if (this._textures) {
  65659. for (var i = 0; i < this._textures.length; i++) {
  65660. this._textures[i].wrapU = wrap;
  65661. }
  65662. }
  65663. },
  65664. enumerable: true,
  65665. configurable: true
  65666. });
  65667. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  65668. set: function (wrap) {
  65669. if (this._textures) {
  65670. for (var i = 0; i < this._textures.length; i++) {
  65671. this._textures[i].wrapV = wrap;
  65672. }
  65673. }
  65674. },
  65675. enumerable: true,
  65676. configurable: true
  65677. });
  65678. MultiRenderTarget.prototype._rebuild = function () {
  65679. this.releaseInternalTextures();
  65680. this._createInternalTextures();
  65681. for (var i = 0; i < this._internalTextures.length; i++) {
  65682. var texture = this._textures[i];
  65683. texture._texture = this._internalTextures[i];
  65684. }
  65685. // Keeps references to frame buffer and stencil/depth buffer
  65686. this._texture = this._internalTextures[0];
  65687. };
  65688. MultiRenderTarget.prototype._createInternalTextures = function () {
  65689. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  65690. };
  65691. MultiRenderTarget.prototype._createTextures = function () {
  65692. this._textures = [];
  65693. for (var i = 0; i < this._internalTextures.length; i++) {
  65694. var texture = new BABYLON.Texture(null, this.getScene());
  65695. texture._texture = this._internalTextures[i];
  65696. this._textures.push(texture);
  65697. }
  65698. // Keeps references to frame buffer and stencil/depth buffer
  65699. this._texture = this._internalTextures[0];
  65700. };
  65701. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  65702. get: function () {
  65703. return this._samples;
  65704. },
  65705. set: function (value) {
  65706. if (this._samples === value) {
  65707. return;
  65708. }
  65709. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  65710. },
  65711. enumerable: true,
  65712. configurable: true
  65713. });
  65714. MultiRenderTarget.prototype.resize = function (size) {
  65715. this.releaseInternalTextures();
  65716. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  65717. this._createInternalTextures();
  65718. };
  65719. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65720. var _this = this;
  65721. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  65722. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65723. });
  65724. };
  65725. MultiRenderTarget.prototype.dispose = function () {
  65726. this.releaseInternalTextures();
  65727. _super.prototype.dispose.call(this);
  65728. };
  65729. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  65730. if (!this._internalTextures) {
  65731. return;
  65732. }
  65733. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  65734. if (this._internalTextures[i] !== undefined) {
  65735. this._internalTextures[i].dispose();
  65736. this._internalTextures.splice(i, 1);
  65737. }
  65738. }
  65739. };
  65740. return MultiRenderTarget;
  65741. }(BABYLON.RenderTargetTexture));
  65742. BABYLON.MultiRenderTarget = MultiRenderTarget;
  65743. })(BABYLON || (BABYLON = {}));
  65744. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  65745. var BABYLON;
  65746. (function (BABYLON) {
  65747. var MirrorTexture = /** @class */ (function (_super) {
  65748. __extends(MirrorTexture, _super);
  65749. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  65750. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65752. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65753. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  65754. _this.scene = scene;
  65755. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  65756. _this._transformMatrix = BABYLON.Matrix.Zero();
  65757. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  65758. _this._adaptiveBlurKernel = 0;
  65759. _this._blurKernelX = 0;
  65760. _this._blurKernelY = 0;
  65761. _this._blurRatio = 1.0;
  65762. _this.ignoreCameraViewport = true;
  65763. _this._updateGammaSpace();
  65764. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  65765. _this._updateGammaSpace;
  65766. });
  65767. _this.onBeforeRenderObservable.add(function () {
  65768. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  65769. _this._savedViewMatrix = scene.getViewMatrix();
  65770. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  65771. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  65772. scene.clipPlane = _this.mirrorPlane;
  65773. scene.getEngine().cullBackFaces = false;
  65774. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  65775. });
  65776. _this.onAfterRenderObservable.add(function () {
  65777. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  65778. scene.getEngine().cullBackFaces = true;
  65779. scene._mirroredCameraPosition = null;
  65780. delete scene.clipPlane;
  65781. });
  65782. return _this;
  65783. }
  65784. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  65785. get: function () {
  65786. return this._blurRatio;
  65787. },
  65788. set: function (value) {
  65789. if (this._blurRatio === value) {
  65790. return;
  65791. }
  65792. this._blurRatio = value;
  65793. this._preparePostProcesses();
  65794. },
  65795. enumerable: true,
  65796. configurable: true
  65797. });
  65798. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  65799. set: function (value) {
  65800. this._adaptiveBlurKernel = value;
  65801. this._autoComputeBlurKernel();
  65802. },
  65803. enumerable: true,
  65804. configurable: true
  65805. });
  65806. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  65807. set: function (value) {
  65808. this.blurKernelX = value;
  65809. this.blurKernelY = value;
  65810. },
  65811. enumerable: true,
  65812. configurable: true
  65813. });
  65814. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  65815. get: function () {
  65816. return this._blurKernelX;
  65817. },
  65818. set: function (value) {
  65819. if (this._blurKernelX === value) {
  65820. return;
  65821. }
  65822. this._blurKernelX = value;
  65823. this._preparePostProcesses();
  65824. },
  65825. enumerable: true,
  65826. configurable: true
  65827. });
  65828. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  65829. get: function () {
  65830. return this._blurKernelY;
  65831. },
  65832. set: function (value) {
  65833. if (this._blurKernelY === value) {
  65834. return;
  65835. }
  65836. this._blurKernelY = value;
  65837. this._preparePostProcesses();
  65838. },
  65839. enumerable: true,
  65840. configurable: true
  65841. });
  65842. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  65843. var engine = this.getScene().getEngine();
  65844. var dw = this.getRenderWidth() / engine.getRenderWidth();
  65845. var dh = this.getRenderHeight() / engine.getRenderHeight();
  65846. this.blurKernelX = this._adaptiveBlurKernel * dw;
  65847. this.blurKernelY = this._adaptiveBlurKernel * dh;
  65848. };
  65849. MirrorTexture.prototype._onRatioRescale = function () {
  65850. if (this._sizeRatio) {
  65851. this.resize(this._initialSizeParameter);
  65852. if (!this._adaptiveBlurKernel) {
  65853. this._preparePostProcesses();
  65854. }
  65855. }
  65856. if (this._adaptiveBlurKernel) {
  65857. this._autoComputeBlurKernel();
  65858. }
  65859. };
  65860. MirrorTexture.prototype._updateGammaSpace = function () {
  65861. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  65862. };
  65863. MirrorTexture.prototype._preparePostProcesses = function () {
  65864. this.clearPostProcesses(true);
  65865. if (this._blurKernelX && this._blurKernelY) {
  65866. var engine = this.getScene().getEngine();
  65867. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65868. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  65869. this._blurX.autoClear = false;
  65870. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  65871. this._blurX.inputTexture = this._texture;
  65872. }
  65873. else {
  65874. this._blurX.alwaysForcePOT = true;
  65875. }
  65876. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  65877. this._blurY.autoClear = false;
  65878. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  65879. this.addPostProcess(this._blurX);
  65880. this.addPostProcess(this._blurY);
  65881. }
  65882. else {
  65883. if (this._blurY) {
  65884. this.removePostProcess(this._blurY);
  65885. this._blurY.dispose();
  65886. this._blurY = null;
  65887. }
  65888. if (this._blurX) {
  65889. this.removePostProcess(this._blurX);
  65890. this._blurX.dispose();
  65891. this._blurX = null;
  65892. }
  65893. }
  65894. };
  65895. MirrorTexture.prototype.clone = function () {
  65896. var scene = this.getScene();
  65897. if (!scene) {
  65898. return this;
  65899. }
  65900. var textureSize = this.getSize();
  65901. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  65902. // Base texture
  65903. newTexture.hasAlpha = this.hasAlpha;
  65904. newTexture.level = this.level;
  65905. // Mirror Texture
  65906. newTexture.mirrorPlane = this.mirrorPlane.clone();
  65907. if (this.renderList) {
  65908. newTexture.renderList = this.renderList.slice(0);
  65909. }
  65910. return newTexture;
  65911. };
  65912. MirrorTexture.prototype.serialize = function () {
  65913. if (!this.name) {
  65914. return null;
  65915. }
  65916. var serializationObject = _super.prototype.serialize.call(this);
  65917. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  65918. return serializationObject;
  65919. };
  65920. MirrorTexture.prototype.dispose = function () {
  65921. _super.prototype.dispose.call(this);
  65922. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  65923. };
  65924. return MirrorTexture;
  65925. }(BABYLON.RenderTargetTexture));
  65926. BABYLON.MirrorTexture = MirrorTexture;
  65927. })(BABYLON || (BABYLON = {}));
  65928. //# sourceMappingURL=babylon.mirrorTexture.js.map
  65929. var BABYLON;
  65930. (function (BABYLON) {
  65931. /**
  65932. * Creates a refraction texture used by refraction channel of the standard material.
  65933. * @param name the texture name
  65934. * @param size size of the underlying texture
  65935. * @param scene root scene
  65936. */
  65937. var RefractionTexture = /** @class */ (function (_super) {
  65938. __extends(RefractionTexture, _super);
  65939. function RefractionTexture(name, size, scene, generateMipMaps) {
  65940. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  65941. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  65942. _this.depth = 2.0;
  65943. _this.onBeforeRenderObservable.add(function () {
  65944. scene.clipPlane = _this.refractionPlane;
  65945. });
  65946. _this.onAfterRenderObservable.add(function () {
  65947. delete scene.clipPlane;
  65948. });
  65949. return _this;
  65950. }
  65951. RefractionTexture.prototype.clone = function () {
  65952. var scene = this.getScene();
  65953. if (!scene) {
  65954. return this;
  65955. }
  65956. var textureSize = this.getSize();
  65957. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  65958. // Base texture
  65959. newTexture.hasAlpha = this.hasAlpha;
  65960. newTexture.level = this.level;
  65961. // Refraction Texture
  65962. newTexture.refractionPlane = this.refractionPlane.clone();
  65963. if (this.renderList) {
  65964. newTexture.renderList = this.renderList.slice(0);
  65965. }
  65966. newTexture.depth = this.depth;
  65967. return newTexture;
  65968. };
  65969. RefractionTexture.prototype.serialize = function () {
  65970. if (!this.name) {
  65971. return null;
  65972. }
  65973. var serializationObject = _super.prototype.serialize.call(this);
  65974. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  65975. serializationObject.depth = this.depth;
  65976. return serializationObject;
  65977. };
  65978. return RefractionTexture;
  65979. }(BABYLON.RenderTargetTexture));
  65980. BABYLON.RefractionTexture = RefractionTexture;
  65981. })(BABYLON || (BABYLON = {}));
  65982. //# sourceMappingURL=babylon.refractionTexture.js.map
  65983. var BABYLON;
  65984. (function (BABYLON) {
  65985. /**
  65986. * A class extending {BABYLON.Texture} allowing drawing on a texture
  65987. * @see http://doc.babylonjs.com/how_to/dynamictexture
  65988. */
  65989. var DynamicTexture = /** @class */ (function (_super) {
  65990. __extends(DynamicTexture, _super);
  65991. /**
  65992. * Creates a {BABYLON.DynamicTexture}
  65993. * @param name defines the name of the texture
  65994. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  65995. * @param scene defines the scene where you want the texture
  65996. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  65997. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  65998. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  65999. */
  66000. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  66001. if (scene === void 0) { scene = null; }
  66002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66003. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66004. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  66005. _this.name = name;
  66006. _this._engine = _this.getScene().getEngine();
  66007. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66008. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66009. _this._generateMipMaps = generateMipMaps;
  66010. if (options.getContext) {
  66011. _this._canvas = options;
  66012. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66013. }
  66014. else {
  66015. _this._canvas = document.createElement("canvas");
  66016. if (options.width || options.width === 0) {
  66017. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66018. }
  66019. else {
  66020. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  66021. }
  66022. }
  66023. var textureSize = _this.getSize();
  66024. _this._canvas.width = textureSize.width;
  66025. _this._canvas.height = textureSize.height;
  66026. _this._context = _this._canvas.getContext("2d");
  66027. return _this;
  66028. }
  66029. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  66030. /**
  66031. * Gets the current state of canRescale
  66032. */
  66033. get: function () {
  66034. return true;
  66035. },
  66036. enumerable: true,
  66037. configurable: true
  66038. });
  66039. DynamicTexture.prototype._recreate = function (textureSize) {
  66040. this._canvas.width = textureSize.width;
  66041. this._canvas.height = textureSize.height;
  66042. this.releaseInternalTexture();
  66043. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  66044. };
  66045. /**
  66046. * Scales the texture
  66047. * @param ratio the scale factor to apply to both width and height
  66048. */
  66049. DynamicTexture.prototype.scale = function (ratio) {
  66050. var textureSize = this.getSize();
  66051. textureSize.width *= ratio;
  66052. textureSize.height *= ratio;
  66053. this._recreate(textureSize);
  66054. };
  66055. /**
  66056. * Resizes the texture
  66057. * @param width the new width
  66058. * @param height the new height
  66059. */
  66060. DynamicTexture.prototype.scaleTo = function (width, height) {
  66061. var textureSize = this.getSize();
  66062. textureSize.width = width;
  66063. textureSize.height = height;
  66064. this._recreate(textureSize);
  66065. };
  66066. /**
  66067. * Gets the context of the canvas used by the texture
  66068. * @returns the canvas context of the dynamic texture
  66069. */
  66070. DynamicTexture.prototype.getContext = function () {
  66071. return this._context;
  66072. };
  66073. /**
  66074. * Clears the texture
  66075. */
  66076. DynamicTexture.prototype.clear = function () {
  66077. var size = this.getSize();
  66078. this._context.fillRect(0, 0, size.width, size.height);
  66079. };
  66080. /**
  66081. * Updates the texture
  66082. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66083. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  66084. */
  66085. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  66086. if (premulAlpha === void 0) { premulAlpha = false; }
  66087. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  66088. };
  66089. /**
  66090. * Draws text onto the texture
  66091. * @param text defines the text to be drawn
  66092. * @param x defines the placement of the text from the left
  66093. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  66094. * @param font defines the font to be used with font-style, font-size, font-name
  66095. * @param color defines the color used for the text
  66096. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  66097. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66098. * @param update defines whether texture is immediately update (default is true)
  66099. */
  66100. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  66101. if (update === void 0) { update = true; }
  66102. var size = this.getSize();
  66103. if (clearColor) {
  66104. this._context.fillStyle = clearColor;
  66105. this._context.fillRect(0, 0, size.width, size.height);
  66106. }
  66107. this._context.font = font;
  66108. if (x === null || x === undefined) {
  66109. var textSize = this._context.measureText(text);
  66110. x = (size.width - textSize.width) / 2;
  66111. }
  66112. if (y === null || y === undefined) {
  66113. var fontSize = parseInt((font.replace(/\D/g, '')));
  66114. y = (size.height / 2) + (fontSize / 3.65);
  66115. }
  66116. this._context.fillStyle = color;
  66117. this._context.fillText(text, x, y);
  66118. if (update) {
  66119. this.update(invertY);
  66120. }
  66121. };
  66122. /**
  66123. * Clones the texture
  66124. * @returns the clone of the texture.
  66125. */
  66126. DynamicTexture.prototype.clone = function () {
  66127. var scene = this.getScene();
  66128. if (!scene) {
  66129. return this;
  66130. }
  66131. var textureSize = this.getSize();
  66132. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  66133. // Base texture
  66134. newTexture.hasAlpha = this.hasAlpha;
  66135. newTexture.level = this.level;
  66136. // Dynamic Texture
  66137. newTexture.wrapU = this.wrapU;
  66138. newTexture.wrapV = this.wrapV;
  66139. return newTexture;
  66140. };
  66141. /** @hidden */
  66142. DynamicTexture.prototype._rebuild = function () {
  66143. this.update();
  66144. };
  66145. return DynamicTexture;
  66146. }(BABYLON.Texture));
  66147. BABYLON.DynamicTexture = DynamicTexture;
  66148. })(BABYLON || (BABYLON = {}));
  66149. //# sourceMappingURL=babylon.dynamicTexture.js.map
  66150. var BABYLON;
  66151. (function (BABYLON) {
  66152. var VideoTexture = /** @class */ (function (_super) {
  66153. __extends(VideoTexture, _super);
  66154. /**
  66155. * Creates a video texture.
  66156. * Sample : https://doc.babylonjs.com/how_to/video_texture
  66157. * @param {string | null} name optional name, will detect from video source, if not defined
  66158. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  66159. * @param {BABYLON.Scene} scene is obviously the current scene.
  66160. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  66161. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  66162. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  66163. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  66164. */
  66165. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  66166. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66167. if (invertY === void 0) { invertY = false; }
  66168. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66169. if (settings === void 0) { settings = {
  66170. autoPlay: true,
  66171. loop: true,
  66172. autoUpdateTexture: true,
  66173. }; }
  66174. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66175. _this._onUserActionRequestedObservable = null;
  66176. _this._stillImageCaptured = false;
  66177. _this._poster = false;
  66178. _this._createInternalTexture = function () {
  66179. if (_this._texture != null) {
  66180. if (_this._poster) {
  66181. _this._texture.dispose();
  66182. _this._poster = false;
  66183. }
  66184. else {
  66185. return;
  66186. }
  66187. }
  66188. if (!_this._engine.needPOTTextures ||
  66189. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  66190. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66191. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66192. }
  66193. else {
  66194. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66195. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66196. _this._generateMipMaps = false;
  66197. }
  66198. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  66199. if (!_this.video.autoplay) {
  66200. var oldHandler_1 = _this.video.onplaying;
  66201. var error_1 = false;
  66202. _this.video.onplaying = function () {
  66203. _this.video.onplaying = oldHandler_1;
  66204. _this._texture.isReady = true;
  66205. _this._updateInternalTexture();
  66206. if (!error_1) {
  66207. _this.video.pause();
  66208. }
  66209. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66210. _this.onLoadObservable.notifyObservers(_this);
  66211. }
  66212. };
  66213. var playing = _this.video.play();
  66214. if (playing) {
  66215. playing.then(function () {
  66216. // Everything is good.
  66217. })
  66218. .catch(function () {
  66219. error_1 = true;
  66220. // On Chrome for instance, new policies might prevent playing without user interaction.
  66221. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  66222. _this._onUserActionRequestedObservable.notifyObservers(_this);
  66223. }
  66224. });
  66225. }
  66226. else {
  66227. _this.video.onplaying = oldHandler_1;
  66228. _this._texture.isReady = true;
  66229. _this._updateInternalTexture();
  66230. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66231. _this.onLoadObservable.notifyObservers(_this);
  66232. }
  66233. }
  66234. }
  66235. else {
  66236. _this._texture.isReady = true;
  66237. _this._updateInternalTexture();
  66238. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66239. _this.onLoadObservable.notifyObservers(_this);
  66240. }
  66241. }
  66242. };
  66243. _this.reset = function () {
  66244. if (_this._texture == null) {
  66245. return;
  66246. }
  66247. if (!_this._poster) {
  66248. _this._texture.dispose();
  66249. _this._texture = null;
  66250. }
  66251. };
  66252. _this._updateInternalTexture = function (e) {
  66253. if (_this._texture == null || !_this._texture.isReady) {
  66254. return;
  66255. }
  66256. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  66257. return;
  66258. }
  66259. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  66260. };
  66261. _this._engine = _this.getScene().getEngine();
  66262. _this._generateMipMaps = generateMipMaps;
  66263. _this._samplingMode = samplingMode;
  66264. _this.autoUpdateTexture = settings.autoUpdateTexture;
  66265. _this.name = name || _this._getName(src);
  66266. _this.video = _this._getVideo(src);
  66267. if (settings.poster) {
  66268. _this.video.poster = settings.poster;
  66269. }
  66270. if (settings.autoPlay !== undefined) {
  66271. _this.video.autoplay = settings.autoPlay;
  66272. }
  66273. if (settings.loop !== undefined) {
  66274. _this.video.loop = settings.loop;
  66275. }
  66276. _this.video.setAttribute("playsinline", "");
  66277. _this.video.addEventListener("canplay", _this._createInternalTexture);
  66278. _this.video.addEventListener("paused", _this._updateInternalTexture);
  66279. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  66280. _this.video.addEventListener("emptied", _this.reset);
  66281. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  66282. _this._createInternalTexture();
  66283. }
  66284. if (settings.poster) {
  66285. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  66286. _this._poster = true;
  66287. }
  66288. return _this;
  66289. }
  66290. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  66291. get: function () {
  66292. if (!this._onUserActionRequestedObservable) {
  66293. this._onUserActionRequestedObservable = new BABYLON.Observable();
  66294. }
  66295. return this._onUserActionRequestedObservable;
  66296. },
  66297. enumerable: true,
  66298. configurable: true
  66299. });
  66300. VideoTexture.prototype._getName = function (src) {
  66301. if (src instanceof HTMLVideoElement) {
  66302. return src.currentSrc;
  66303. }
  66304. if (typeof src === "object") {
  66305. return src.toString();
  66306. }
  66307. return src;
  66308. };
  66309. ;
  66310. VideoTexture.prototype._getVideo = function (src) {
  66311. if (src instanceof HTMLVideoElement) {
  66312. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  66313. return src;
  66314. }
  66315. var video = document.createElement("video");
  66316. if (typeof src === "string") {
  66317. BABYLON.Tools.SetCorsBehavior(src, video);
  66318. video.src = src;
  66319. }
  66320. else {
  66321. BABYLON.Tools.SetCorsBehavior(src[0], video);
  66322. src.forEach(function (url) {
  66323. var source = document.createElement("source");
  66324. source.src = url;
  66325. video.appendChild(source);
  66326. });
  66327. }
  66328. return video;
  66329. };
  66330. ;
  66331. /**
  66332. * Internal method to initiate `update`.
  66333. */
  66334. VideoTexture.prototype._rebuild = function () {
  66335. this.update();
  66336. };
  66337. /**
  66338. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  66339. */
  66340. VideoTexture.prototype.update = function () {
  66341. if (!this.autoUpdateTexture) {
  66342. // Expecting user to call `updateTexture` manually
  66343. return;
  66344. }
  66345. this.updateTexture(true);
  66346. };
  66347. /**
  66348. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  66349. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  66350. */
  66351. VideoTexture.prototype.updateTexture = function (isVisible) {
  66352. if (!isVisible) {
  66353. return;
  66354. }
  66355. if (this.video.paused && this._stillImageCaptured) {
  66356. return;
  66357. }
  66358. this._stillImageCaptured = true;
  66359. this._updateInternalTexture();
  66360. };
  66361. /**
  66362. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  66363. * @param url New url.
  66364. */
  66365. VideoTexture.prototype.updateURL = function (url) {
  66366. this.video.src = url;
  66367. };
  66368. VideoTexture.prototype.dispose = function () {
  66369. _super.prototype.dispose.call(this);
  66370. if (this._onUserActionRequestedObservable) {
  66371. this._onUserActionRequestedObservable.clear();
  66372. this._onUserActionRequestedObservable = null;
  66373. }
  66374. this.video.removeEventListener("canplay", this._createInternalTexture);
  66375. this.video.removeEventListener("paused", this._updateInternalTexture);
  66376. this.video.removeEventListener("seeked", this._updateInternalTexture);
  66377. this.video.removeEventListener("emptied", this.reset);
  66378. this.video.pause();
  66379. };
  66380. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  66381. var video = document.createElement("video");
  66382. video.setAttribute('autoplay', '');
  66383. video.setAttribute('muted', '');
  66384. video.setAttribute('playsinline', '');
  66385. var constraintsDeviceId;
  66386. if (constraints && constraints.deviceId) {
  66387. constraintsDeviceId = {
  66388. exact: constraints.deviceId,
  66389. };
  66390. }
  66391. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  66392. if (navigator.mediaDevices) {
  66393. navigator.mediaDevices.getUserMedia({ video: constraints })
  66394. .then(function (stream) {
  66395. if (video.mozSrcObject !== undefined) {
  66396. // hack for Firefox < 19
  66397. video.mozSrcObject = stream;
  66398. }
  66399. else {
  66400. video.srcObject = stream;
  66401. }
  66402. var onPlaying = function () {
  66403. if (onReady) {
  66404. onReady(new VideoTexture("video", video, scene, true, true));
  66405. }
  66406. video.removeEventListener("playing", onPlaying);
  66407. };
  66408. video.addEventListener("playing", onPlaying);
  66409. video.play();
  66410. })
  66411. .catch(function (err) {
  66412. BABYLON.Tools.Error(err.name);
  66413. });
  66414. }
  66415. else {
  66416. navigator.getUserMedia =
  66417. navigator.getUserMedia ||
  66418. navigator.webkitGetUserMedia ||
  66419. navigator.mozGetUserMedia ||
  66420. navigator.msGetUserMedia;
  66421. if (navigator.getUserMedia) {
  66422. navigator.getUserMedia({
  66423. video: {
  66424. deviceId: constraintsDeviceId,
  66425. width: {
  66426. min: (constraints && constraints.minWidth) || 256,
  66427. max: (constraints && constraints.maxWidth) || 640,
  66428. },
  66429. height: {
  66430. min: (constraints && constraints.minHeight) || 256,
  66431. max: (constraints && constraints.maxHeight) || 480,
  66432. },
  66433. },
  66434. }, function (stream) {
  66435. if (video.mozSrcObject !== undefined) {
  66436. // hack for Firefox < 19
  66437. video.mozSrcObject = stream;
  66438. }
  66439. else {
  66440. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  66441. }
  66442. video.play();
  66443. if (onReady) {
  66444. onReady(new VideoTexture("video", video, scene, true, true));
  66445. }
  66446. }, function (e) {
  66447. BABYLON.Tools.Error(e.name);
  66448. });
  66449. }
  66450. }
  66451. };
  66452. return VideoTexture;
  66453. }(BABYLON.Texture));
  66454. BABYLON.VideoTexture = VideoTexture;
  66455. })(BABYLON || (BABYLON = {}));
  66456. //# sourceMappingURL=babylon.videoTexture.js.map
  66457. var BABYLON;
  66458. (function (BABYLON) {
  66459. var RawTexture = /** @class */ (function (_super) {
  66460. __extends(RawTexture, _super);
  66461. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  66462. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66463. if (invertY === void 0) { invertY = false; }
  66464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66465. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66466. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66467. _this.format = format;
  66468. _this._engine = scene.getEngine();
  66469. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  66470. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66471. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66472. return _this;
  66473. }
  66474. RawTexture.prototype.update = function (data) {
  66475. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66476. };
  66477. // Statics
  66478. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66479. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66480. if (invertY === void 0) { invertY = false; }
  66481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66482. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  66483. };
  66484. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66485. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66486. if (invertY === void 0) { invertY = false; }
  66487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66488. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66489. };
  66490. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66491. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66492. if (invertY === void 0) { invertY = false; }
  66493. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66494. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66495. };
  66496. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66497. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66498. if (invertY === void 0) { invertY = false; }
  66499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66500. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66501. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  66502. };
  66503. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66504. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66505. if (invertY === void 0) { invertY = false; }
  66506. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66507. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66508. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  66509. };
  66510. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66511. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66512. if (invertY === void 0) { invertY = false; }
  66513. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66514. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66515. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  66516. };
  66517. return RawTexture;
  66518. }(BABYLON.Texture));
  66519. BABYLON.RawTexture = RawTexture;
  66520. })(BABYLON || (BABYLON = {}));
  66521. //# sourceMappingURL=babylon.rawTexture.js.map
  66522. var BABYLON;
  66523. (function (BABYLON) {
  66524. /**
  66525. * Class used to store 3D textures containing user data
  66526. */
  66527. var RawTexture3D = /** @class */ (function (_super) {
  66528. __extends(RawTexture3D, _super);
  66529. /**
  66530. * Create a new RawTexture3D
  66531. * @param data defines the data of the texture
  66532. * @param width defines the width of the texture
  66533. * @param height defines the height of the texture
  66534. * @param depth defines the depth of the texture
  66535. * @param format defines the texture format to use
  66536. * @param scene defines the hosting scene
  66537. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  66538. * @param invertY defines if texture must be stored with Y axis inverted
  66539. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  66540. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  66541. */
  66542. function RawTexture3D(data, width, height, depth,
  66543. /** Gets or sets the texture format to use */
  66544. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  66545. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66546. if (invertY === void 0) { invertY = false; }
  66547. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66548. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66549. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66550. _this.format = format;
  66551. _this._engine = scene.getEngine();
  66552. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  66553. _this.is3D = true;
  66554. return _this;
  66555. }
  66556. /**
  66557. * Update the texture with new data
  66558. * @param data defines the data to store in the texture
  66559. */
  66560. RawTexture3D.prototype.update = function (data) {
  66561. if (!this._texture) {
  66562. return;
  66563. }
  66564. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66565. };
  66566. return RawTexture3D;
  66567. }(BABYLON.Texture));
  66568. BABYLON.RawTexture3D = RawTexture3D;
  66569. })(BABYLON || (BABYLON = {}));
  66570. //# sourceMappingURL=babylon.rawTexture3D.js.map
  66571. var BABYLON;
  66572. (function (BABYLON) {
  66573. /**
  66574. * PostProcessManager is used to manage one or more post processes or post process pipelines
  66575. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66576. */
  66577. var PostProcessManager = /** @class */ (function () {
  66578. /**
  66579. * Creates a new instance PostProcess
  66580. * @param scene The scene that the post process is associated with.
  66581. */
  66582. function PostProcessManager(scene) {
  66583. this._vertexBuffers = {};
  66584. this._scene = scene;
  66585. }
  66586. PostProcessManager.prototype._prepareBuffers = function () {
  66587. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  66588. return;
  66589. }
  66590. // VBO
  66591. var vertices = [];
  66592. vertices.push(1, 1);
  66593. vertices.push(-1, 1);
  66594. vertices.push(-1, -1);
  66595. vertices.push(1, -1);
  66596. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66597. this._buildIndexBuffer();
  66598. };
  66599. PostProcessManager.prototype._buildIndexBuffer = function () {
  66600. // Indices
  66601. var indices = [];
  66602. indices.push(0);
  66603. indices.push(1);
  66604. indices.push(2);
  66605. indices.push(0);
  66606. indices.push(2);
  66607. indices.push(3);
  66608. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  66609. };
  66610. /**
  66611. * Rebuilds the vertex buffers of the manager.
  66612. */
  66613. PostProcessManager.prototype._rebuild = function () {
  66614. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66615. if (!vb) {
  66616. return;
  66617. }
  66618. vb._rebuild();
  66619. this._buildIndexBuffer();
  66620. };
  66621. // Methods
  66622. /**
  66623. * Prepares a frame to be run through a post process.
  66624. * @param sourceTexture The input texture to the post procesess. (default: null)
  66625. * @param postProcesses An array of post processes to be run. (default: null)
  66626. * @returns True if the post processes were able to be run.
  66627. */
  66628. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  66629. if (sourceTexture === void 0) { sourceTexture = null; }
  66630. if (postProcesses === void 0) { postProcesses = null; }
  66631. var camera = this._scene.activeCamera;
  66632. if (!camera) {
  66633. return false;
  66634. }
  66635. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66636. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66637. return false;
  66638. }
  66639. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  66640. return true;
  66641. };
  66642. /**
  66643. * Manually render a set of post processes to a texture.
  66644. * @param postProcesses An array of post processes to be run.
  66645. * @param targetTexture The target texture to render to.
  66646. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  66647. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  66648. * @param lodLevel defines which lod of the texture to render to
  66649. */
  66650. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  66651. if (targetTexture === void 0) { targetTexture = null; }
  66652. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66653. if (faceIndex === void 0) { faceIndex = 0; }
  66654. if (lodLevel === void 0) { lodLevel = 0; }
  66655. var engine = this._scene.getEngine();
  66656. for (var index = 0; index < postProcesses.length; index++) {
  66657. if (index < postProcesses.length - 1) {
  66658. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  66659. }
  66660. else {
  66661. if (targetTexture) {
  66662. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  66663. }
  66664. else {
  66665. engine.restoreDefaultFramebuffer();
  66666. }
  66667. }
  66668. var pp = postProcesses[index];
  66669. var effect = pp.apply();
  66670. if (effect) {
  66671. pp.onBeforeRenderObservable.notifyObservers(effect);
  66672. // VBOs
  66673. this._prepareBuffers();
  66674. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66675. // Draw order
  66676. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66677. pp.onAfterRenderObservable.notifyObservers(effect);
  66678. }
  66679. }
  66680. // Restore depth buffer
  66681. engine.setDepthBuffer(true);
  66682. engine.setDepthWrite(true);
  66683. };
  66684. /**
  66685. * Finalize the result of the output of the postprocesses.
  66686. * @param doNotPresent If true the result will not be displayed to the screen.
  66687. * @param targetTexture The target texture to render to.
  66688. * @param faceIndex The index of the face to bind the target texture to.
  66689. * @param postProcesses The array of post processes to render.
  66690. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  66691. */
  66692. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  66693. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66694. var camera = this._scene.activeCamera;
  66695. if (!camera) {
  66696. return;
  66697. }
  66698. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66699. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66700. return;
  66701. }
  66702. var engine = this._scene.getEngine();
  66703. for (var index = 0, len = postProcesses.length; index < len; index++) {
  66704. var pp = postProcesses[index];
  66705. if (index < len - 1) {
  66706. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  66707. }
  66708. else {
  66709. if (targetTexture) {
  66710. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  66711. pp._outputTexture = targetTexture;
  66712. }
  66713. else {
  66714. engine.restoreDefaultFramebuffer();
  66715. pp._outputTexture = null;
  66716. }
  66717. }
  66718. if (doNotPresent) {
  66719. break;
  66720. }
  66721. var effect = pp.apply();
  66722. if (effect) {
  66723. pp.onBeforeRenderObservable.notifyObservers(effect);
  66724. // VBOs
  66725. this._prepareBuffers();
  66726. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66727. // Draw order
  66728. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66729. pp.onAfterRenderObservable.notifyObservers(effect);
  66730. }
  66731. }
  66732. // Restore states
  66733. engine.setDepthBuffer(true);
  66734. engine.setDepthWrite(true);
  66735. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66736. };
  66737. /**
  66738. * Disposes of the post process manager.
  66739. */
  66740. PostProcessManager.prototype.dispose = function () {
  66741. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66742. if (buffer) {
  66743. buffer.dispose();
  66744. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66745. }
  66746. if (this._indexBuffer) {
  66747. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66748. this._indexBuffer = null;
  66749. }
  66750. };
  66751. return PostProcessManager;
  66752. }());
  66753. BABYLON.PostProcessManager = PostProcessManager;
  66754. })(BABYLON || (BABYLON = {}));
  66755. //# sourceMappingURL=babylon.postProcessManager.js.map
  66756. var BABYLON;
  66757. (function (BABYLON) {
  66758. /**
  66759. * PostProcess can be used to apply a shader to a texture after it has been rendered
  66760. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66761. */
  66762. var PostProcess = /** @class */ (function () {
  66763. /**
  66764. * Creates a new instance PostProcess
  66765. * @param name The name of the PostProcess.
  66766. * @param fragmentUrl The url of the fragment shader to be used.
  66767. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  66768. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  66769. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66770. * @param camera The camera to apply the render pass to.
  66771. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66772. * @param engine The engine which the post process will be applied. (default: current engine)
  66773. * @param reusable If the post process can be reused on the same frame. (default: false)
  66774. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  66775. * @param textureType Type of textures used when performing the post process. (default: 0)
  66776. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  66777. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  66778. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  66779. */
  66780. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  66781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  66782. if (defines === void 0) { defines = null; }
  66783. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66784. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  66785. if (blockCompilation === void 0) { blockCompilation = false; }
  66786. this.name = name;
  66787. /**
  66788. * Width of the texture to apply the post process on
  66789. */
  66790. this.width = -1;
  66791. /**
  66792. * Height of the texture to apply the post process on
  66793. */
  66794. this.height = -1;
  66795. /**
  66796. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  66797. */
  66798. this._outputTexture = null;
  66799. /**
  66800. * If the buffer needs to be cleared before applying the post process. (default: true)
  66801. * Should be set to false if shader will overwrite all previous pixels.
  66802. */
  66803. this.autoClear = true;
  66804. /**
  66805. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  66806. */
  66807. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  66808. /**
  66809. * Animations to be used for the post processing
  66810. */
  66811. this.animations = new Array();
  66812. /**
  66813. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  66814. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  66815. */
  66816. this.enablePixelPerfectMode = false;
  66817. /**
  66818. * Force the postprocess to be applied without taking in account viewport
  66819. */
  66820. this.forceFullscreenViewport = true;
  66821. /**
  66822. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  66823. *
  66824. * | Value | Type | Description |
  66825. * | ----- | ----------------------------------- | ----------- |
  66826. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  66827. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  66828. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  66829. *
  66830. */
  66831. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  66832. /**
  66833. * Force textures to be a power of two (default: false)
  66834. */
  66835. this.alwaysForcePOT = false;
  66836. /**
  66837. * Number of sample textures (default: 1)
  66838. */
  66839. this.samples = 1;
  66840. /**
  66841. * Modify the scale of the post process to be the same as the viewport (default: false)
  66842. */
  66843. this.adaptScaleToCurrentViewport = false;
  66844. this._reusable = false;
  66845. /**
  66846. * Smart array of input and output textures for the post process.
  66847. */
  66848. this._textures = new BABYLON.SmartArray(2);
  66849. /**
  66850. * The index in _textures that corresponds to the output texture.
  66851. */
  66852. this._currentRenderTextureInd = 0;
  66853. this._scaleRatio = new BABYLON.Vector2(1, 1);
  66854. this._texelSize = BABYLON.Vector2.Zero();
  66855. // Events
  66856. /**
  66857. * An event triggered when the postprocess is activated.
  66858. */
  66859. this.onActivateObservable = new BABYLON.Observable();
  66860. /**
  66861. * An event triggered when the postprocess changes its size.
  66862. */
  66863. this.onSizeChangedObservable = new BABYLON.Observable();
  66864. /**
  66865. * An event triggered when the postprocess applies its effect.
  66866. */
  66867. this.onApplyObservable = new BABYLON.Observable();
  66868. /**
  66869. * An event triggered before rendering the postprocess
  66870. */
  66871. this.onBeforeRenderObservable = new BABYLON.Observable();
  66872. /**
  66873. * An event triggered after rendering the postprocess
  66874. */
  66875. this.onAfterRenderObservable = new BABYLON.Observable();
  66876. if (camera != null) {
  66877. this._camera = camera;
  66878. this._scene = camera.getScene();
  66879. camera.attachPostProcess(this);
  66880. this._engine = this._scene.getEngine();
  66881. this._scene.postProcesses.push(this);
  66882. }
  66883. else if (engine) {
  66884. this._engine = engine;
  66885. this._engine.postProcesses.push(this);
  66886. }
  66887. this._options = options;
  66888. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  66889. this._reusable = reusable || false;
  66890. this._textureType = textureType;
  66891. this._samplers = samplers || [];
  66892. this._samplers.push("textureSampler");
  66893. this._fragmentUrl = fragmentUrl;
  66894. this._vertexUrl = vertexUrl;
  66895. this._parameters = parameters || [];
  66896. this._parameters.push("scale");
  66897. this._indexParameters = indexParameters;
  66898. if (!blockCompilation) {
  66899. this.updateEffect(defines);
  66900. }
  66901. }
  66902. Object.defineProperty(PostProcess.prototype, "onActivate", {
  66903. /**
  66904. * A function that is added to the onActivateObservable
  66905. */
  66906. set: function (callback) {
  66907. if (this._onActivateObserver) {
  66908. this.onActivateObservable.remove(this._onActivateObserver);
  66909. }
  66910. if (callback) {
  66911. this._onActivateObserver = this.onActivateObservable.add(callback);
  66912. }
  66913. },
  66914. enumerable: true,
  66915. configurable: true
  66916. });
  66917. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  66918. /**
  66919. * A function that is added to the onSizeChangedObservable
  66920. */
  66921. set: function (callback) {
  66922. if (this._onSizeChangedObserver) {
  66923. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  66924. }
  66925. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  66926. },
  66927. enumerable: true,
  66928. configurable: true
  66929. });
  66930. Object.defineProperty(PostProcess.prototype, "onApply", {
  66931. /**
  66932. * A function that is added to the onApplyObservable
  66933. */
  66934. set: function (callback) {
  66935. if (this._onApplyObserver) {
  66936. this.onApplyObservable.remove(this._onApplyObserver);
  66937. }
  66938. this._onApplyObserver = this.onApplyObservable.add(callback);
  66939. },
  66940. enumerable: true,
  66941. configurable: true
  66942. });
  66943. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  66944. /**
  66945. * A function that is added to the onBeforeRenderObservable
  66946. */
  66947. set: function (callback) {
  66948. if (this._onBeforeRenderObserver) {
  66949. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66950. }
  66951. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66952. },
  66953. enumerable: true,
  66954. configurable: true
  66955. });
  66956. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  66957. /**
  66958. * A function that is added to the onAfterRenderObservable
  66959. */
  66960. set: function (callback) {
  66961. if (this._onAfterRenderObserver) {
  66962. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66963. }
  66964. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66965. },
  66966. enumerable: true,
  66967. configurable: true
  66968. });
  66969. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  66970. /**
  66971. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  66972. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  66973. */
  66974. get: function () {
  66975. return this._textures.data[this._currentRenderTextureInd];
  66976. },
  66977. set: function (value) {
  66978. this._forcedOutputTexture = value;
  66979. },
  66980. enumerable: true,
  66981. configurable: true
  66982. });
  66983. /**
  66984. * Gets the camera which post process is applied to.
  66985. * @returns The camera the post process is applied to.
  66986. */
  66987. PostProcess.prototype.getCamera = function () {
  66988. return this._camera;
  66989. };
  66990. Object.defineProperty(PostProcess.prototype, "texelSize", {
  66991. /**
  66992. * Gets the texel size of the postprocess.
  66993. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  66994. */
  66995. get: function () {
  66996. if (this._shareOutputWithPostProcess) {
  66997. return this._shareOutputWithPostProcess.texelSize;
  66998. }
  66999. if (this._forcedOutputTexture) {
  67000. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  67001. }
  67002. return this._texelSize;
  67003. },
  67004. enumerable: true,
  67005. configurable: true
  67006. });
  67007. /**
  67008. * Gets the engine which this post process belongs to.
  67009. * @returns The engine the post process was enabled with.
  67010. */
  67011. PostProcess.prototype.getEngine = function () {
  67012. return this._engine;
  67013. };
  67014. /**
  67015. * The effect that is created when initializing the post process.
  67016. * @returns The created effect corrisponding the the postprocess.
  67017. */
  67018. PostProcess.prototype.getEffect = function () {
  67019. return this._effect;
  67020. };
  67021. /**
  67022. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  67023. * @param postProcess The post process to share the output with.
  67024. * @returns This post process.
  67025. */
  67026. PostProcess.prototype.shareOutputWith = function (postProcess) {
  67027. this._disposeTextures();
  67028. this._shareOutputWithPostProcess = postProcess;
  67029. return this;
  67030. };
  67031. /**
  67032. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  67033. * This should be called if the post process that shares output with this post process is disabled/disposed.
  67034. */
  67035. PostProcess.prototype.useOwnOutput = function () {
  67036. if (this._textures.length == 0) {
  67037. this._textures = new BABYLON.SmartArray(2);
  67038. }
  67039. this._shareOutputWithPostProcess = null;
  67040. };
  67041. /**
  67042. * Updates the effect with the current post process compile time values and recompiles the shader.
  67043. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  67044. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  67045. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  67046. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  67047. * @param onCompiled Called when the shader has been compiled.
  67048. * @param onError Called if there is an error when compiling a shader.
  67049. */
  67050. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  67051. if (defines === void 0) { defines = null; }
  67052. if (uniforms === void 0) { uniforms = null; }
  67053. if (samplers === void 0) { samplers = null; }
  67054. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : "", undefined, onCompiled, onError, indexParameters || this._indexParameters);
  67055. };
  67056. /**
  67057. * The post process is reusable if it can be used multiple times within one frame.
  67058. * @returns If the post process is reusable
  67059. */
  67060. PostProcess.prototype.isReusable = function () {
  67061. return this._reusable;
  67062. };
  67063. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  67064. PostProcess.prototype.markTextureDirty = function () {
  67065. this.width = -1;
  67066. };
  67067. /**
  67068. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  67069. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  67070. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  67071. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  67072. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  67073. * @returns The target texture that was bound to be written to.
  67074. */
  67075. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  67076. var _this = this;
  67077. if (sourceTexture === void 0) { sourceTexture = null; }
  67078. camera = camera || this._camera;
  67079. var scene = camera.getScene();
  67080. var engine = scene.getEngine();
  67081. var maxSize = engine.getCaps().maxTextureSize;
  67082. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  67083. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  67084. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  67085. var webVRCamera = camera.parent;
  67086. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  67087. requiredWidth /= 2;
  67088. }
  67089. var desiredWidth = (this._options.width || requiredWidth);
  67090. var desiredHeight = this._options.height || requiredHeight;
  67091. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  67092. if (this.adaptScaleToCurrentViewport) {
  67093. var currentViewport = engine.currentViewport;
  67094. if (currentViewport) {
  67095. desiredWidth *= currentViewport.width;
  67096. desiredHeight *= currentViewport.height;
  67097. }
  67098. }
  67099. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  67100. if (!this._options.width) {
  67101. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  67102. }
  67103. if (!this._options.height) {
  67104. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  67105. }
  67106. }
  67107. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  67108. if (this._textures.length > 0) {
  67109. for (var i = 0; i < this._textures.length; i++) {
  67110. this._engine._releaseTexture(this._textures.data[i]);
  67111. }
  67112. this._textures.reset();
  67113. }
  67114. this.width = desiredWidth;
  67115. this.height = desiredHeight;
  67116. var textureSize = { width: this.width, height: this.height };
  67117. var textureOptions = {
  67118. generateMipMaps: false,
  67119. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  67120. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  67121. samplingMode: this.renderTargetSamplingMode,
  67122. type: this._textureType
  67123. };
  67124. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67125. if (this._reusable) {
  67126. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67127. }
  67128. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  67129. this.onSizeChangedObservable.notifyObservers(this);
  67130. }
  67131. this._textures.forEach(function (texture) {
  67132. if (texture.samples !== _this.samples) {
  67133. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  67134. }
  67135. });
  67136. }
  67137. var target;
  67138. if (this._shareOutputWithPostProcess) {
  67139. target = this._shareOutputWithPostProcess.inputTexture;
  67140. }
  67141. else if (this._forcedOutputTexture) {
  67142. target = this._forcedOutputTexture;
  67143. this.width = this._forcedOutputTexture.width;
  67144. this.height = this._forcedOutputTexture.height;
  67145. }
  67146. else {
  67147. target = this.inputTexture;
  67148. }
  67149. // Bind the input of this post process to be used as the output of the previous post process.
  67150. if (this.enablePixelPerfectMode) {
  67151. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  67152. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  67153. }
  67154. else {
  67155. this._scaleRatio.copyFromFloats(1, 1);
  67156. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  67157. }
  67158. this.onActivateObservable.notifyObservers(camera);
  67159. // Clear
  67160. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  67161. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  67162. }
  67163. if (this._reusable) {
  67164. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  67165. }
  67166. return target;
  67167. };
  67168. Object.defineProperty(PostProcess.prototype, "isSupported", {
  67169. /**
  67170. * If the post process is supported.
  67171. */
  67172. get: function () {
  67173. return this._effect.isSupported;
  67174. },
  67175. enumerable: true,
  67176. configurable: true
  67177. });
  67178. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  67179. /**
  67180. * The aspect ratio of the output texture.
  67181. */
  67182. get: function () {
  67183. if (this._shareOutputWithPostProcess) {
  67184. return this._shareOutputWithPostProcess.aspectRatio;
  67185. }
  67186. if (this._forcedOutputTexture) {
  67187. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  67188. }
  67189. return this.width / this.height;
  67190. },
  67191. enumerable: true,
  67192. configurable: true
  67193. });
  67194. /**
  67195. * Get a value indicating if the post-process is ready to be used
  67196. * @returns true if the post-process is ready (shader is compiled)
  67197. */
  67198. PostProcess.prototype.isReady = function () {
  67199. return this._effect && this._effect.isReady();
  67200. };
  67201. /**
  67202. * Binds all textures and uniforms to the shader, this will be run on every pass.
  67203. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  67204. */
  67205. PostProcess.prototype.apply = function () {
  67206. // Check
  67207. if (!this._effect || !this._effect.isReady())
  67208. return null;
  67209. // States
  67210. this._engine.enableEffect(this._effect);
  67211. this._engine.setState(false);
  67212. this._engine.setDepthBuffer(false);
  67213. this._engine.setDepthWrite(false);
  67214. // Alpha
  67215. this._engine.setAlphaMode(this.alphaMode);
  67216. if (this.alphaConstants) {
  67217. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  67218. }
  67219. // Bind the output texture of the preivous post process as the input to this post process.
  67220. var source;
  67221. if (this._shareOutputWithPostProcess) {
  67222. source = this._shareOutputWithPostProcess.inputTexture;
  67223. }
  67224. else if (this._forcedOutputTexture) {
  67225. source = this._forcedOutputTexture;
  67226. }
  67227. else {
  67228. source = this.inputTexture;
  67229. }
  67230. this._effect._bindTexture("textureSampler", source);
  67231. // Parameters
  67232. this._effect.setVector2("scale", this._scaleRatio);
  67233. this.onApplyObservable.notifyObservers(this._effect);
  67234. return this._effect;
  67235. };
  67236. PostProcess.prototype._disposeTextures = function () {
  67237. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  67238. return;
  67239. }
  67240. if (this._textures.length > 0) {
  67241. for (var i = 0; i < this._textures.length; i++) {
  67242. this._engine._releaseTexture(this._textures.data[i]);
  67243. }
  67244. }
  67245. this._textures.dispose();
  67246. };
  67247. /**
  67248. * Disposes the post process.
  67249. * @param camera The camera to dispose the post process on.
  67250. */
  67251. PostProcess.prototype.dispose = function (camera) {
  67252. camera = camera || this._camera;
  67253. this._disposeTextures();
  67254. if (this._scene) {
  67255. var index_1 = this._scene.postProcesses.indexOf(this);
  67256. if (index_1 !== -1) {
  67257. this._scene.postProcesses.splice(index_1, 1);
  67258. }
  67259. }
  67260. else {
  67261. var index_2 = this._engine.postProcesses.indexOf(this);
  67262. if (index_2 !== -1) {
  67263. this._engine.postProcesses.splice(index_2, 1);
  67264. }
  67265. }
  67266. if (!camera) {
  67267. return;
  67268. }
  67269. camera.detachPostProcess(this);
  67270. var index = camera._postProcesses.indexOf(this);
  67271. if (index === 0 && camera._postProcesses.length > 0) {
  67272. var firstPostProcess = this._camera._getFirstPostProcess();
  67273. if (firstPostProcess) {
  67274. firstPostProcess.markTextureDirty();
  67275. }
  67276. }
  67277. this.onActivateObservable.clear();
  67278. this.onAfterRenderObservable.clear();
  67279. this.onApplyObservable.clear();
  67280. this.onBeforeRenderObservable.clear();
  67281. this.onSizeChangedObservable.clear();
  67282. };
  67283. return PostProcess;
  67284. }());
  67285. BABYLON.PostProcess = PostProcess;
  67286. })(BABYLON || (BABYLON = {}));
  67287. //# sourceMappingURL=babylon.postProcess.js.map
  67288. var BABYLON;
  67289. (function (BABYLON) {
  67290. var PassPostProcess = /** @class */ (function (_super) {
  67291. __extends(PassPostProcess, _super);
  67292. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67293. if (camera === void 0) { camera = null; }
  67294. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67295. if (blockCompilation === void 0) { blockCompilation = false; }
  67296. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  67297. }
  67298. return PassPostProcess;
  67299. }(BABYLON.PostProcess));
  67300. BABYLON.PassPostProcess = PassPostProcess;
  67301. })(BABYLON || (BABYLON = {}));
  67302. //# sourceMappingURL=babylon.passPostProcess.js.map
  67303. var __assign = (this && this.__assign) || Object.assign || function(t) {
  67304. for (var s, i = 1, n = arguments.length; i < n; i++) {
  67305. s = arguments[i];
  67306. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  67307. t[p] = s[p];
  67308. }
  67309. return t;
  67310. };
  67311. var BABYLON;
  67312. (function (BABYLON) {
  67313. /**
  67314. * Default implementation IShadowGenerator.
  67315. * This is the main object responsible of generating shadows in the framework.
  67316. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  67317. */
  67318. var ShadowGenerator = /** @class */ (function () {
  67319. /**
  67320. * Creates a ShadowGenerator object.
  67321. * A ShadowGenerator is the required tool to use the shadows.
  67322. * Each light casting shadows needs to use its own ShadowGenerator.
  67323. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  67324. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  67325. * @param light The light object generating the shadows.
  67326. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  67327. */
  67328. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  67329. this._bias = 0.00005;
  67330. this._normalBias = 0;
  67331. this._blurBoxOffset = 1;
  67332. this._blurScale = 2;
  67333. this._blurKernel = 1;
  67334. this._useKernelBlur = false;
  67335. this._filter = ShadowGenerator.FILTER_NONE;
  67336. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  67337. this._contactHardeningLightSizeUVRatio = 0.1;
  67338. this._darkness = 0;
  67339. this._transparencyShadow = false;
  67340. /**
  67341. * Controls the extent to which the shadows fade out at the edge of the frustum
  67342. * Used only by directionals and spots
  67343. */
  67344. this.frustumEdgeFalloff = 0;
  67345. /**
  67346. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  67347. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  67348. * It might on the other hand introduce peter panning.
  67349. */
  67350. this.forceBackFacesOnly = false;
  67351. this._lightDirection = BABYLON.Vector3.Zero();
  67352. this._viewMatrix = BABYLON.Matrix.Zero();
  67353. this._projectionMatrix = BABYLON.Matrix.Zero();
  67354. this._transformMatrix = BABYLON.Matrix.Zero();
  67355. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67356. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67357. this._currentFaceIndex = 0;
  67358. this._currentFaceIndexCache = 0;
  67359. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  67360. this._mapSize = mapSize;
  67361. this._light = light;
  67362. this._scene = light.getScene();
  67363. light._shadowGenerator = this;
  67364. // Texture type fallback from float to int if not supported.
  67365. var caps = this._scene.getEngine().getCaps();
  67366. if (!useFullFloatFirst) {
  67367. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67368. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67369. }
  67370. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67371. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67372. }
  67373. else {
  67374. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67375. }
  67376. }
  67377. else {
  67378. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67379. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67380. }
  67381. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67382. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67383. }
  67384. else {
  67385. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67386. }
  67387. }
  67388. this._initializeGenerator();
  67389. this._applyFilterValues();
  67390. }
  67391. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  67392. /**
  67393. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  67394. */
  67395. get: function () {
  67396. return this._bias;
  67397. },
  67398. /**
  67399. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  67400. */
  67401. set: function (bias) {
  67402. this._bias = bias;
  67403. },
  67404. enumerable: true,
  67405. configurable: true
  67406. });
  67407. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  67408. /**
  67409. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67410. */
  67411. get: function () {
  67412. return this._normalBias;
  67413. },
  67414. /**
  67415. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67416. */
  67417. set: function (normalBias) {
  67418. this._normalBias = normalBias;
  67419. },
  67420. enumerable: true,
  67421. configurable: true
  67422. });
  67423. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  67424. /**
  67425. * Gets the blur box offset: offset applied during the blur pass.
  67426. * Only usefull if useKernelBlur = false
  67427. */
  67428. get: function () {
  67429. return this._blurBoxOffset;
  67430. },
  67431. /**
  67432. * Sets the blur box offset: offset applied during the blur pass.
  67433. * Only usefull if useKernelBlur = false
  67434. */
  67435. set: function (value) {
  67436. if (this._blurBoxOffset === value) {
  67437. return;
  67438. }
  67439. this._blurBoxOffset = value;
  67440. this._disposeBlurPostProcesses();
  67441. },
  67442. enumerable: true,
  67443. configurable: true
  67444. });
  67445. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  67446. /**
  67447. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  67448. * 2 means half of the size.
  67449. */
  67450. get: function () {
  67451. return this._blurScale;
  67452. },
  67453. /**
  67454. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  67455. * 2 means half of the size.
  67456. */
  67457. set: function (value) {
  67458. if (this._blurScale === value) {
  67459. return;
  67460. }
  67461. this._blurScale = value;
  67462. this._disposeBlurPostProcesses();
  67463. },
  67464. enumerable: true,
  67465. configurable: true
  67466. });
  67467. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  67468. /**
  67469. * Gets the blur kernel: kernel size of the blur pass.
  67470. * Only usefull if useKernelBlur = true
  67471. */
  67472. get: function () {
  67473. return this._blurKernel;
  67474. },
  67475. /**
  67476. * Sets the blur kernel: kernel size of the blur pass.
  67477. * Only usefull if useKernelBlur = true
  67478. */
  67479. set: function (value) {
  67480. if (this._blurKernel === value) {
  67481. return;
  67482. }
  67483. this._blurKernel = value;
  67484. this._disposeBlurPostProcesses();
  67485. },
  67486. enumerable: true,
  67487. configurable: true
  67488. });
  67489. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  67490. /**
  67491. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  67492. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67493. */
  67494. get: function () {
  67495. return this._useKernelBlur;
  67496. },
  67497. /**
  67498. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  67499. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67500. */
  67501. set: function (value) {
  67502. if (this._useKernelBlur === value) {
  67503. return;
  67504. }
  67505. this._useKernelBlur = value;
  67506. this._disposeBlurPostProcesses();
  67507. },
  67508. enumerable: true,
  67509. configurable: true
  67510. });
  67511. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  67512. /**
  67513. * Gets the depth scale used in ESM mode.
  67514. */
  67515. get: function () {
  67516. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  67517. },
  67518. /**
  67519. * Sets the depth scale used in ESM mode.
  67520. * This can override the scale stored on the light.
  67521. */
  67522. set: function (value) {
  67523. this._depthScale = value;
  67524. },
  67525. enumerable: true,
  67526. configurable: true
  67527. });
  67528. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  67529. /**
  67530. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  67531. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67532. */
  67533. get: function () {
  67534. return this._filter;
  67535. },
  67536. /**
  67537. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  67538. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67539. */
  67540. set: function (value) {
  67541. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  67542. if (this._light.needCube()) {
  67543. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67544. this.useExponentialShadowMap = true;
  67545. return;
  67546. }
  67547. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67548. this.useCloseExponentialShadowMap = true;
  67549. return;
  67550. }
  67551. // PCF on cubemap would also be expensive
  67552. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67553. this.usePoissonSampling = true;
  67554. return;
  67555. }
  67556. }
  67557. // Weblg1 fallback for PCF.
  67558. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67559. if (this._scene.getEngine().webGLVersion === 1) {
  67560. this.usePoissonSampling = true;
  67561. return;
  67562. }
  67563. }
  67564. if (this._filter === value) {
  67565. return;
  67566. }
  67567. this._filter = value;
  67568. this._disposeBlurPostProcesses();
  67569. this._applyFilterValues();
  67570. this._light._markMeshesAsLightDirty();
  67571. },
  67572. enumerable: true,
  67573. configurable: true
  67574. });
  67575. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  67576. /**
  67577. * Gets if the current filter is set to Poisson Sampling.
  67578. */
  67579. get: function () {
  67580. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  67581. },
  67582. /**
  67583. * Sets the current filter to Poisson Sampling.
  67584. */
  67585. set: function (value) {
  67586. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  67587. return;
  67588. }
  67589. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  67590. },
  67591. enumerable: true,
  67592. configurable: true
  67593. });
  67594. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  67595. /**
  67596. * Gets if the current filter is set to VSM.
  67597. * DEPRECATED. Should use useExponentialShadowMap instead.
  67598. */
  67599. get: function () {
  67600. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67601. return this.useExponentialShadowMap;
  67602. },
  67603. /**
  67604. * Sets the current filter is to VSM.
  67605. * DEPRECATED. Should use useExponentialShadowMap instead.
  67606. */
  67607. set: function (value) {
  67608. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67609. this.useExponentialShadowMap = value;
  67610. },
  67611. enumerable: true,
  67612. configurable: true
  67613. });
  67614. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  67615. /**
  67616. * Gets if the current filter is set to blurred VSM.
  67617. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67618. */
  67619. get: function () {
  67620. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67621. return this.useBlurExponentialShadowMap;
  67622. },
  67623. /**
  67624. * Sets the current filter is to blurred VSM.
  67625. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67626. */
  67627. set: function (value) {
  67628. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67629. this.useBlurExponentialShadowMap = value;
  67630. },
  67631. enumerable: true,
  67632. configurable: true
  67633. });
  67634. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  67635. /**
  67636. * Gets if the current filter is set to ESM.
  67637. */
  67638. get: function () {
  67639. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  67640. },
  67641. /**
  67642. * Sets the current filter is to ESM.
  67643. */
  67644. set: function (value) {
  67645. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  67646. return;
  67647. }
  67648. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67649. },
  67650. enumerable: true,
  67651. configurable: true
  67652. });
  67653. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  67654. /**
  67655. * Gets if the current filter is set to filtered ESM.
  67656. */
  67657. get: function () {
  67658. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  67659. },
  67660. /**
  67661. * Gets if the current filter is set to filtered ESM.
  67662. */
  67663. set: function (value) {
  67664. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67665. return;
  67666. }
  67667. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67668. },
  67669. enumerable: true,
  67670. configurable: true
  67671. });
  67672. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  67673. /**
  67674. * Gets if the current filter is set to "close ESM" (using the inverse of the
  67675. * exponential to prevent steep falloff artifacts).
  67676. */
  67677. get: function () {
  67678. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  67679. },
  67680. /**
  67681. * Sets the current filter to "close ESM" (using the inverse of the
  67682. * exponential to prevent steep falloff artifacts).
  67683. */
  67684. set: function (value) {
  67685. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  67686. return;
  67687. }
  67688. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67689. },
  67690. enumerable: true,
  67691. configurable: true
  67692. });
  67693. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  67694. /**
  67695. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  67696. * exponential to prevent steep falloff artifacts).
  67697. */
  67698. get: function () {
  67699. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  67700. },
  67701. /**
  67702. * Sets the current filter to filtered "close ESM" (using the inverse of the
  67703. * exponential to prevent steep falloff artifacts).
  67704. */
  67705. set: function (value) {
  67706. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67707. return;
  67708. }
  67709. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67710. },
  67711. enumerable: true,
  67712. configurable: true
  67713. });
  67714. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  67715. /**
  67716. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  67717. */
  67718. get: function () {
  67719. return this.filter === ShadowGenerator.FILTER_PCF;
  67720. },
  67721. /**
  67722. * Sets the current filter to "PCF" (percentage closer filtering).
  67723. */
  67724. set: function (value) {
  67725. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  67726. return;
  67727. }
  67728. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  67729. },
  67730. enumerable: true,
  67731. configurable: true
  67732. });
  67733. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  67734. /**
  67735. * Gets the PCF or PCSS Quality.
  67736. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67737. */
  67738. get: function () {
  67739. return this._filteringQuality;
  67740. },
  67741. /**
  67742. * Sets the PCF or PCSS Quality.
  67743. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67744. */
  67745. set: function (filteringQuality) {
  67746. this._filteringQuality = filteringQuality;
  67747. },
  67748. enumerable: true,
  67749. configurable: true
  67750. });
  67751. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  67752. /**
  67753. * Gets if the current filter is set to "PCSS" (contact hardening).
  67754. */
  67755. get: function () {
  67756. return this.filter === ShadowGenerator.FILTER_PCSS;
  67757. },
  67758. /**
  67759. * Sets the current filter to "PCSS" (contact hardening).
  67760. */
  67761. set: function (value) {
  67762. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  67763. return;
  67764. }
  67765. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  67766. },
  67767. enumerable: true,
  67768. configurable: true
  67769. });
  67770. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  67771. /**
  67772. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67773. * Using a ratio helps keeping shape stability independently of the map size.
  67774. *
  67775. * It does not account for the light projection as it was having too much
  67776. * instability during the light setup or during light position changes.
  67777. *
  67778. * Only valid if useContactHardeningShadow is true.
  67779. */
  67780. get: function () {
  67781. return this._contactHardeningLightSizeUVRatio;
  67782. },
  67783. /**
  67784. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67785. * Using a ratio helps keeping shape stability independently of the map size.
  67786. *
  67787. * It does not account for the light projection as it was having too much
  67788. * instability during the light setup or during light position changes.
  67789. *
  67790. * Only valid if useContactHardeningShadow is true.
  67791. */
  67792. set: function (contactHardeningLightSizeUVRatio) {
  67793. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  67794. },
  67795. enumerable: true,
  67796. configurable: true
  67797. });
  67798. /**
  67799. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  67800. * 0 means strongest and 1 would means no shadow.
  67801. * @returns the darkness.
  67802. */
  67803. ShadowGenerator.prototype.getDarkness = function () {
  67804. return this._darkness;
  67805. };
  67806. /**
  67807. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  67808. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  67809. * @returns the shadow generator allowing fluent coding.
  67810. */
  67811. ShadowGenerator.prototype.setDarkness = function (darkness) {
  67812. if (darkness >= 1.0)
  67813. this._darkness = 1.0;
  67814. else if (darkness <= 0.0)
  67815. this._darkness = 0.0;
  67816. else
  67817. this._darkness = darkness;
  67818. return this;
  67819. };
  67820. /**
  67821. * Sets the ability to have transparent shadow (boolean).
  67822. * @param transparent True if transparent else False
  67823. * @returns the shadow generator allowing fluent coding
  67824. */
  67825. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  67826. this._transparencyShadow = transparent;
  67827. return this;
  67828. };
  67829. /**
  67830. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  67831. * @returns The render target texture if present otherwise, null
  67832. */
  67833. ShadowGenerator.prototype.getShadowMap = function () {
  67834. return this._shadowMap;
  67835. };
  67836. /**
  67837. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  67838. * @returns The render target texture if the shadow map is present otherwise, null
  67839. */
  67840. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  67841. if (this._shadowMap2) {
  67842. return this._shadowMap2;
  67843. }
  67844. return this._shadowMap;
  67845. };
  67846. /**
  67847. * Helper function to add a mesh and its descendants to the list of shadow casters.
  67848. * @param mesh Mesh to add
  67849. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  67850. * @returns the Shadow Generator itself
  67851. */
  67852. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  67853. if (includeDescendants === void 0) { includeDescendants = true; }
  67854. if (!this._shadowMap) {
  67855. return this;
  67856. }
  67857. if (!this._shadowMap.renderList) {
  67858. this._shadowMap.renderList = [];
  67859. }
  67860. this._shadowMap.renderList.push(mesh);
  67861. if (includeDescendants) {
  67862. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  67863. }
  67864. return this;
  67865. var _a;
  67866. };
  67867. /**
  67868. * Helper function to remove a mesh and its descendants from the list of shadow casters
  67869. * @param mesh Mesh to remove
  67870. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  67871. * @returns the Shadow Generator itself
  67872. */
  67873. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  67874. if (includeDescendants === void 0) { includeDescendants = true; }
  67875. if (!this._shadowMap || !this._shadowMap.renderList) {
  67876. return this;
  67877. }
  67878. var index = this._shadowMap.renderList.indexOf(mesh);
  67879. if (index !== -1) {
  67880. this._shadowMap.renderList.splice(index, 1);
  67881. }
  67882. if (includeDescendants) {
  67883. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  67884. var child = _a[_i];
  67885. this.removeShadowCaster(child);
  67886. }
  67887. }
  67888. return this;
  67889. };
  67890. /**
  67891. * Returns the associated light object.
  67892. * @returns the light generating the shadow
  67893. */
  67894. ShadowGenerator.prototype.getLight = function () {
  67895. return this._light;
  67896. };
  67897. ShadowGenerator.prototype._initializeGenerator = function () {
  67898. this._light._markMeshesAsLightDirty();
  67899. this._initializeShadowMap();
  67900. };
  67901. ShadowGenerator.prototype._initializeShadowMap = function () {
  67902. var _this = this;
  67903. // Render target
  67904. var engine = this._scene.getEngine();
  67905. if (engine.webGLVersion > 1) {
  67906. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  67907. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  67908. }
  67909. else {
  67910. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  67911. }
  67912. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67913. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67914. this._shadowMap.anisotropicFilteringLevel = 1;
  67915. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67916. this._shadowMap.renderParticles = false;
  67917. this._shadowMap.ignoreCameraViewport = true;
  67918. // Record Face Index before render.
  67919. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  67920. _this._currentFaceIndex = faceIndex;
  67921. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67922. engine.setColorWrite(false);
  67923. }
  67924. });
  67925. // Custom render function.
  67926. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  67927. // Blur if required afer render.
  67928. this._shadowMap.onAfterUnbindObservable.add(function () {
  67929. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67930. engine.setColorWrite(true);
  67931. }
  67932. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  67933. return;
  67934. }
  67935. var shadowMap = _this.getShadowMapForRendering();
  67936. if (shadowMap) {
  67937. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  67938. }
  67939. });
  67940. // Clear according to the chosen filter.
  67941. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  67942. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67943. this._shadowMap.onClearObservable.add(function (engine) {
  67944. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67945. engine.clear(clearOne, false, true, false);
  67946. }
  67947. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  67948. engine.clear(clearZero, true, true, false);
  67949. }
  67950. else {
  67951. engine.clear(clearOne, true, true, false);
  67952. }
  67953. });
  67954. };
  67955. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  67956. var _this = this;
  67957. var engine = this._scene.getEngine();
  67958. var targetSize = this._mapSize / this.blurScale;
  67959. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  67960. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  67961. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67962. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67963. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67964. }
  67965. if (this.useKernelBlur) {
  67966. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  67967. this._kernelBlurXPostprocess.width = targetSize;
  67968. this._kernelBlurXPostprocess.height = targetSize;
  67969. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  67970. effect.setTexture("textureSampler", _this._shadowMap);
  67971. });
  67972. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  67973. this._kernelBlurXPostprocess.autoClear = false;
  67974. this._kernelBlurYPostprocess.autoClear = false;
  67975. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67976. this._kernelBlurXPostprocess.packedFloat = true;
  67977. this._kernelBlurYPostprocess.packedFloat = true;
  67978. }
  67979. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  67980. }
  67981. else {
  67982. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  67983. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  67984. effect.setFloat2("screenSize", targetSize, targetSize);
  67985. effect.setTexture("textureSampler", _this._shadowMap);
  67986. });
  67987. this._boxBlurPostprocess.autoClear = false;
  67988. this._blurPostProcesses = [this._boxBlurPostprocess];
  67989. }
  67990. };
  67991. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67992. var index;
  67993. var engine = this._scene.getEngine();
  67994. if (depthOnlySubMeshes.length) {
  67995. engine.setColorWrite(false);
  67996. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67997. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  67998. }
  67999. engine.setColorWrite(true);
  68000. }
  68001. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68002. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  68003. }
  68004. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68005. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  68006. }
  68007. if (this._transparencyShadow) {
  68008. for (index = 0; index < transparentSubMeshes.length; index++) {
  68009. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  68010. }
  68011. }
  68012. };
  68013. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  68014. var _this = this;
  68015. var mesh = subMesh.getRenderingMesh();
  68016. var scene = this._scene;
  68017. var engine = scene.getEngine();
  68018. var material = subMesh.getMaterial();
  68019. if (!material) {
  68020. return;
  68021. }
  68022. // Culling
  68023. engine.setState(material.backFaceCulling);
  68024. // Managing instances
  68025. var batch = mesh._getInstancesRenderList(subMesh._id);
  68026. if (batch.mustReturn) {
  68027. return;
  68028. }
  68029. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68030. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  68031. engine.enableEffect(this._effect);
  68032. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68033. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  68034. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  68035. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68036. this._effect.setVector3("lightData", this._cachedDirection);
  68037. }
  68038. else {
  68039. this._effect.setVector3("lightData", this._cachedPosition);
  68040. }
  68041. if (scene.activeCamera) {
  68042. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  68043. }
  68044. // Alpha test
  68045. if (material && material.needAlphaTesting()) {
  68046. var alphaTexture = material.getAlphaTestTexture();
  68047. if (alphaTexture) {
  68048. this._effect.setTexture("diffuseSampler", alphaTexture);
  68049. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  68050. }
  68051. }
  68052. // Bones
  68053. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68054. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  68055. }
  68056. // Morph targets
  68057. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  68058. if (this.forceBackFacesOnly) {
  68059. engine.setState(true, 0, false, true);
  68060. }
  68061. // Draw
  68062. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68063. if (this.forceBackFacesOnly) {
  68064. engine.setState(true, 0, false, false);
  68065. }
  68066. }
  68067. else {
  68068. // Need to reset refresh rate of the shadowMap
  68069. if (this._shadowMap) {
  68070. this._shadowMap.resetRefreshCounter();
  68071. }
  68072. }
  68073. };
  68074. ShadowGenerator.prototype._applyFilterValues = function () {
  68075. if (!this._shadowMap) {
  68076. return;
  68077. }
  68078. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  68079. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68080. }
  68081. else {
  68082. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68083. }
  68084. };
  68085. /**
  68086. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68087. * @param onCompiled Callback triggered at the and of the effects compilation
  68088. * @param options Sets of optional options forcing the compilation with different modes
  68089. */
  68090. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  68091. var _this = this;
  68092. var localOptions = __assign({ useInstances: false }, options);
  68093. var shadowMap = this.getShadowMap();
  68094. if (!shadowMap) {
  68095. if (onCompiled) {
  68096. onCompiled(this);
  68097. }
  68098. return;
  68099. }
  68100. var renderList = shadowMap.renderList;
  68101. if (!renderList) {
  68102. if (onCompiled) {
  68103. onCompiled(this);
  68104. }
  68105. return;
  68106. }
  68107. var subMeshes = new Array();
  68108. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  68109. var mesh = renderList_1[_i];
  68110. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  68111. }
  68112. if (subMeshes.length === 0) {
  68113. if (onCompiled) {
  68114. onCompiled(this);
  68115. }
  68116. return;
  68117. }
  68118. var currentIndex = 0;
  68119. var checkReady = function () {
  68120. if (!_this._scene || !_this._scene.getEngine()) {
  68121. return;
  68122. }
  68123. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  68124. currentIndex++;
  68125. if (currentIndex >= subMeshes.length) {
  68126. if (onCompiled) {
  68127. onCompiled(_this);
  68128. }
  68129. return;
  68130. }
  68131. }
  68132. setTimeout(checkReady, 16);
  68133. };
  68134. checkReady();
  68135. };
  68136. /**
  68137. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68138. * @param options Sets of optional options forcing the compilation with different modes
  68139. * @returns A promise that resolves when the compilation completes
  68140. */
  68141. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  68142. var _this = this;
  68143. return new Promise(function (resolve) {
  68144. _this.forceCompilation(function () {
  68145. resolve();
  68146. }, options);
  68147. });
  68148. };
  68149. /**
  68150. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  68151. * @param subMesh The submesh we want to render in the shadow map
  68152. * @param useInstances Defines wether will draw in the map using instances
  68153. * @returns true if ready otherwise, false
  68154. */
  68155. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  68156. var defines = [];
  68157. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68158. defines.push("#define FLOAT");
  68159. }
  68160. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68161. defines.push("#define ESM");
  68162. }
  68163. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  68164. defines.push("#define DEPTHTEXTURE");
  68165. }
  68166. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68167. var mesh = subMesh.getMesh();
  68168. var material = subMesh.getMaterial();
  68169. // Normal bias.
  68170. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68171. attribs.push(BABYLON.VertexBuffer.NormalKind);
  68172. defines.push("#define NORMAL");
  68173. if (mesh.nonUniformScaling) {
  68174. defines.push("#define NONUNIFORMSCALING");
  68175. }
  68176. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68177. defines.push("#define DIRECTIONINLIGHTDATA");
  68178. }
  68179. }
  68180. // Alpha test
  68181. if (material && material.needAlphaTesting()) {
  68182. var alphaTexture = material.getAlphaTestTexture();
  68183. if (alphaTexture) {
  68184. defines.push("#define ALPHATEST");
  68185. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68186. attribs.push(BABYLON.VertexBuffer.UVKind);
  68187. defines.push("#define UV1");
  68188. }
  68189. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68190. if (alphaTexture.coordinatesIndex === 1) {
  68191. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68192. defines.push("#define UV2");
  68193. }
  68194. }
  68195. }
  68196. }
  68197. // Bones
  68198. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68199. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68200. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68201. if (mesh.numBoneInfluencers > 4) {
  68202. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68203. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68204. }
  68205. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68206. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68207. }
  68208. else {
  68209. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68210. }
  68211. // Morph targets
  68212. var manager = mesh.morphTargetManager;
  68213. var morphInfluencers = 0;
  68214. if (manager) {
  68215. if (manager.numInfluencers > 0) {
  68216. defines.push("#define MORPHTARGETS");
  68217. morphInfluencers = manager.numInfluencers;
  68218. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  68219. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  68220. }
  68221. }
  68222. // Instances
  68223. if (useInstances) {
  68224. defines.push("#define INSTANCES");
  68225. attribs.push("world0");
  68226. attribs.push("world1");
  68227. attribs.push("world2");
  68228. attribs.push("world3");
  68229. }
  68230. // Get correct effect
  68231. var join = defines.join("\n");
  68232. if (this._cachedDefines !== join) {
  68233. this._cachedDefines = join;
  68234. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  68235. }
  68236. if (!this._effect.isReady()) {
  68237. return false;
  68238. }
  68239. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68240. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  68241. this._initializeBlurRTTAndPostProcesses();
  68242. }
  68243. }
  68244. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  68245. return false;
  68246. }
  68247. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  68248. return false;
  68249. }
  68250. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  68251. return false;
  68252. }
  68253. return true;
  68254. };
  68255. /**
  68256. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  68257. * @param defines Defines of the material we want to update
  68258. * @param lightIndex Index of the light in the enabled light list of the material
  68259. */
  68260. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  68261. var scene = this._scene;
  68262. var light = this._light;
  68263. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68264. return;
  68265. }
  68266. defines["SHADOW" + lightIndex] = true;
  68267. if (this.useContactHardeningShadow) {
  68268. defines["SHADOWPCSS" + lightIndex] = true;
  68269. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68270. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68271. }
  68272. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68273. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68274. }
  68275. // else default to high.
  68276. }
  68277. if (this.usePercentageCloserFiltering) {
  68278. defines["SHADOWPCF" + lightIndex] = true;
  68279. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68280. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68281. }
  68282. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68283. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68284. }
  68285. // else default to high.
  68286. }
  68287. else if (this.usePoissonSampling) {
  68288. defines["SHADOWPOISSON" + lightIndex] = true;
  68289. }
  68290. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68291. defines["SHADOWESM" + lightIndex] = true;
  68292. }
  68293. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68294. defines["SHADOWCLOSEESM" + lightIndex] = true;
  68295. }
  68296. if (light.needCube()) {
  68297. defines["SHADOWCUBE" + lightIndex] = true;
  68298. }
  68299. };
  68300. /**
  68301. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  68302. * defined in the generator but impacting the effect).
  68303. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  68304. * @param effect The effect we are binfing the information for
  68305. */
  68306. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  68307. var light = this._light;
  68308. var scene = this._scene;
  68309. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68310. return;
  68311. }
  68312. var camera = scene.activeCamera;
  68313. if (!camera) {
  68314. return;
  68315. }
  68316. var shadowMap = this.getShadowMap();
  68317. if (!shadowMap) {
  68318. return;
  68319. }
  68320. if (!light.needCube()) {
  68321. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  68322. }
  68323. // Only PCF uses depth stencil texture.
  68324. if (this._filter === ShadowGenerator.FILTER_PCF) {
  68325. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68326. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68327. }
  68328. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  68329. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68330. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  68331. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68332. }
  68333. else {
  68334. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68335. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  68336. }
  68337. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  68338. };
  68339. /**
  68340. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  68341. * (eq to shadow prjection matrix * light transform matrix)
  68342. * @returns The transform matrix used to create the shadow map
  68343. */
  68344. ShadowGenerator.prototype.getTransformMatrix = function () {
  68345. var scene = this._scene;
  68346. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  68347. return this._transformMatrix;
  68348. }
  68349. this._currentRenderID = scene.getRenderId();
  68350. this._currentFaceIndexCache = this._currentFaceIndex;
  68351. var lightPosition = this._light.position;
  68352. if (this._light.computeTransformedInformation()) {
  68353. lightPosition = this._light.transformedPosition;
  68354. }
  68355. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  68356. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  68357. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  68358. }
  68359. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  68360. this._cachedPosition.copyFrom(lightPosition);
  68361. this._cachedDirection.copyFrom(this._lightDirection);
  68362. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  68363. var shadowMap = this.getShadowMap();
  68364. if (shadowMap) {
  68365. var renderList = shadowMap.renderList;
  68366. if (renderList) {
  68367. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  68368. }
  68369. }
  68370. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  68371. }
  68372. return this._transformMatrix;
  68373. };
  68374. /**
  68375. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  68376. * Cube and 2D textures for instance.
  68377. */
  68378. ShadowGenerator.prototype.recreateShadowMap = function () {
  68379. var shadowMap = this._shadowMap;
  68380. if (!shadowMap) {
  68381. return;
  68382. }
  68383. // Track render list.
  68384. var renderList = shadowMap.renderList;
  68385. // Clean up existing data.
  68386. this._disposeRTTandPostProcesses();
  68387. // Reinitializes.
  68388. this._initializeGenerator();
  68389. // Reaffect the filter to ensure a correct fallback if necessary.
  68390. this.filter = this.filter;
  68391. // Reaffect the filter.
  68392. this._applyFilterValues();
  68393. // Reaffect Render List.
  68394. this._shadowMap.renderList = renderList;
  68395. };
  68396. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  68397. if (this._shadowMap2) {
  68398. this._shadowMap2.dispose();
  68399. this._shadowMap2 = null;
  68400. }
  68401. if (this._boxBlurPostprocess) {
  68402. this._boxBlurPostprocess.dispose();
  68403. this._boxBlurPostprocess = null;
  68404. }
  68405. if (this._kernelBlurXPostprocess) {
  68406. this._kernelBlurXPostprocess.dispose();
  68407. this._kernelBlurXPostprocess = null;
  68408. }
  68409. if (this._kernelBlurYPostprocess) {
  68410. this._kernelBlurYPostprocess.dispose();
  68411. this._kernelBlurYPostprocess = null;
  68412. }
  68413. this._blurPostProcesses = [];
  68414. };
  68415. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  68416. if (this._shadowMap) {
  68417. this._shadowMap.dispose();
  68418. this._shadowMap = null;
  68419. }
  68420. this._disposeBlurPostProcesses();
  68421. };
  68422. /**
  68423. * Disposes the ShadowGenerator.
  68424. * Returns nothing.
  68425. */
  68426. ShadowGenerator.prototype.dispose = function () {
  68427. this._disposeRTTandPostProcesses();
  68428. if (this._light) {
  68429. this._light._shadowGenerator = null;
  68430. this._light._markMeshesAsLightDirty();
  68431. }
  68432. };
  68433. /**
  68434. * Serializes the shadow generator setup to a json object.
  68435. * @returns The serialized JSON object
  68436. */
  68437. ShadowGenerator.prototype.serialize = function () {
  68438. var serializationObject = {};
  68439. var shadowMap = this.getShadowMap();
  68440. if (!shadowMap) {
  68441. return serializationObject;
  68442. }
  68443. serializationObject.lightId = this._light.id;
  68444. serializationObject.mapSize = shadowMap.getRenderSize();
  68445. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  68446. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  68447. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68448. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68449. serializationObject.usePoissonSampling = this.usePoissonSampling;
  68450. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  68451. serializationObject.depthScale = this.depthScale;
  68452. serializationObject.darkness = this.getDarkness();
  68453. serializationObject.blurBoxOffset = this.blurBoxOffset;
  68454. serializationObject.blurKernel = this.blurKernel;
  68455. serializationObject.blurScale = this.blurScale;
  68456. serializationObject.useKernelBlur = this.useKernelBlur;
  68457. serializationObject.transparencyShadow = this._transparencyShadow;
  68458. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  68459. serializationObject.bias = this.bias;
  68460. serializationObject.normalBias = this.normalBias;
  68461. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  68462. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  68463. serializationObject.filteringQuality = this.filteringQuality;
  68464. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  68465. serializationObject.renderList = [];
  68466. if (shadowMap.renderList) {
  68467. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  68468. var mesh = shadowMap.renderList[meshIndex];
  68469. serializationObject.renderList.push(mesh.id);
  68470. }
  68471. }
  68472. return serializationObject;
  68473. };
  68474. /**
  68475. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  68476. * @param parsedShadowGenerator The JSON object to parse
  68477. * @param scene The scene to create the shadow map for
  68478. * @returns The parsed shadow generator
  68479. */
  68480. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  68481. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  68482. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  68483. var shadowMap = shadowGenerator.getShadowMap();
  68484. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  68485. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  68486. meshes.forEach(function (mesh) {
  68487. if (!shadowMap) {
  68488. return;
  68489. }
  68490. if (!shadowMap.renderList) {
  68491. shadowMap.renderList = [];
  68492. }
  68493. shadowMap.renderList.push(mesh);
  68494. });
  68495. }
  68496. if (parsedShadowGenerator.usePoissonSampling) {
  68497. shadowGenerator.usePoissonSampling = true;
  68498. }
  68499. else if (parsedShadowGenerator.useExponentialShadowMap) {
  68500. shadowGenerator.useExponentialShadowMap = true;
  68501. }
  68502. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  68503. shadowGenerator.useBlurExponentialShadowMap = true;
  68504. }
  68505. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  68506. shadowGenerator.useCloseExponentialShadowMap = true;
  68507. }
  68508. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  68509. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  68510. }
  68511. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  68512. shadowGenerator.usePercentageCloserFiltering = true;
  68513. }
  68514. else if (parsedShadowGenerator.useContactHardeningShadow) {
  68515. shadowGenerator.useContactHardeningShadow = true;
  68516. }
  68517. if (parsedShadowGenerator.filteringQuality) {
  68518. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  68519. }
  68520. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  68521. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  68522. }
  68523. // Backward compat
  68524. else if (parsedShadowGenerator.useVarianceShadowMap) {
  68525. shadowGenerator.useExponentialShadowMap = true;
  68526. }
  68527. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  68528. shadowGenerator.useBlurExponentialShadowMap = true;
  68529. }
  68530. if (parsedShadowGenerator.depthScale) {
  68531. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  68532. }
  68533. if (parsedShadowGenerator.blurScale) {
  68534. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  68535. }
  68536. if (parsedShadowGenerator.blurBoxOffset) {
  68537. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  68538. }
  68539. if (parsedShadowGenerator.useKernelBlur) {
  68540. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  68541. }
  68542. if (parsedShadowGenerator.blurKernel) {
  68543. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  68544. }
  68545. if (parsedShadowGenerator.bias !== undefined) {
  68546. shadowGenerator.bias = parsedShadowGenerator.bias;
  68547. }
  68548. if (parsedShadowGenerator.normalBias !== undefined) {
  68549. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  68550. }
  68551. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  68552. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  68553. }
  68554. if (parsedShadowGenerator.darkness) {
  68555. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  68556. }
  68557. if (parsedShadowGenerator.transparencyShadow) {
  68558. shadowGenerator.setTransparencyShadow(true);
  68559. }
  68560. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  68561. return shadowGenerator;
  68562. };
  68563. /**
  68564. * Shadow generator mode None: no filtering applied.
  68565. */
  68566. ShadowGenerator.FILTER_NONE = 0;
  68567. /**
  68568. * Shadow generator mode ESM: Exponential Shadow Mapping.
  68569. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68570. */
  68571. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  68572. /**
  68573. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  68574. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  68575. */
  68576. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  68577. /**
  68578. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  68579. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68580. */
  68581. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  68582. /**
  68583. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  68584. * edge artifacts on steep falloff.
  68585. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68586. */
  68587. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  68588. /**
  68589. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  68590. * edge artifacts on steep falloff.
  68591. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68592. */
  68593. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  68594. /**
  68595. * Shadow generator mode PCF: Percentage Closer Filtering
  68596. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68597. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  68598. */
  68599. ShadowGenerator.FILTER_PCF = 6;
  68600. /**
  68601. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  68602. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68603. * Contact Hardening
  68604. */
  68605. ShadowGenerator.FILTER_PCSS = 7;
  68606. /**
  68607. * Reserved for PCF and PCSS
  68608. * Highest Quality.
  68609. *
  68610. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  68611. *
  68612. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  68613. */
  68614. ShadowGenerator.QUALITY_HIGH = 0;
  68615. /**
  68616. * Reserved for PCF and PCSS
  68617. * Good tradeoff for quality/perf cross devices
  68618. *
  68619. * Execute PCF on a 3*3 kernel.
  68620. *
  68621. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  68622. */
  68623. ShadowGenerator.QUALITY_MEDIUM = 1;
  68624. /**
  68625. * Reserved for PCF and PCSS
  68626. * The lowest quality but the fastest.
  68627. *
  68628. * Execute PCF on a 1*1 kernel.
  68629. *
  68630. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  68631. */
  68632. ShadowGenerator.QUALITY_LOW = 2;
  68633. return ShadowGenerator;
  68634. }());
  68635. BABYLON.ShadowGenerator = ShadowGenerator;
  68636. })(BABYLON || (BABYLON = {}));
  68637. //# sourceMappingURL=babylon.shadowGenerator.js.map
  68638. var BABYLON;
  68639. (function (BABYLON) {
  68640. var DefaultLoadingScreen = /** @class */ (function () {
  68641. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  68642. if (_loadingText === void 0) { _loadingText = ""; }
  68643. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  68644. var _this = this;
  68645. this._renderingCanvas = _renderingCanvas;
  68646. this._loadingText = _loadingText;
  68647. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  68648. // Resize
  68649. this._resizeLoadingUI = function () {
  68650. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  68651. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  68652. if (!_this._loadingDiv) {
  68653. return;
  68654. }
  68655. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  68656. _this._loadingDiv.style.left = canvasRect.left + "px";
  68657. _this._loadingDiv.style.top = canvasRect.top + "px";
  68658. _this._loadingDiv.style.width = canvasRect.width + "px";
  68659. _this._loadingDiv.style.height = canvasRect.height + "px";
  68660. };
  68661. }
  68662. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  68663. if (this._loadingDiv) {
  68664. // Do not add a loading screen if there is already one
  68665. return;
  68666. }
  68667. this._loadingDiv = document.createElement("div");
  68668. this._loadingDiv.id = "babylonjsLoadingDiv";
  68669. this._loadingDiv.style.opacity = "0";
  68670. this._loadingDiv.style.transition = "opacity 1.5s ease";
  68671. this._loadingDiv.style.pointerEvents = "none";
  68672. // Loading text
  68673. this._loadingTextDiv = document.createElement("div");
  68674. this._loadingTextDiv.style.position = "absolute";
  68675. this._loadingTextDiv.style.left = "0";
  68676. this._loadingTextDiv.style.top = "50%";
  68677. this._loadingTextDiv.style.marginTop = "80px";
  68678. this._loadingTextDiv.style.width = "100%";
  68679. this._loadingTextDiv.style.height = "20px";
  68680. this._loadingTextDiv.style.fontFamily = "Arial";
  68681. this._loadingTextDiv.style.fontSize = "14px";
  68682. this._loadingTextDiv.style.color = "white";
  68683. this._loadingTextDiv.style.textAlign = "center";
  68684. this._loadingTextDiv.innerHTML = "Loading";
  68685. this._loadingDiv.appendChild(this._loadingTextDiv);
  68686. //set the predefined text
  68687. this._loadingTextDiv.innerHTML = this._loadingText;
  68688. // Generating keyframes
  68689. var style = document.createElement('style');
  68690. style.type = 'text/css';
  68691. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  68692. style.innerHTML = keyFrames;
  68693. document.getElementsByTagName('head')[0].appendChild(style);
  68694. // Loading img
  68695. var imgBack = new Image();
  68696. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  68697. imgBack.style.position = "absolute";
  68698. imgBack.style.left = "50%";
  68699. imgBack.style.top = "50%";
  68700. imgBack.style.marginLeft = "-60px";
  68701. imgBack.style.marginTop = "-60px";
  68702. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  68703. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  68704. imgBack.style.transformOrigin = "50% 50%";
  68705. imgBack.style.webkitTransformOrigin = "50% 50%";
  68706. this._loadingDiv.appendChild(imgBack);
  68707. this._resizeLoadingUI();
  68708. window.addEventListener("resize", this._resizeLoadingUI);
  68709. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68710. document.body.appendChild(this._loadingDiv);
  68711. this._loadingDiv.style.opacity = "1";
  68712. };
  68713. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  68714. var _this = this;
  68715. if (!this._loadingDiv) {
  68716. return;
  68717. }
  68718. var onTransitionEnd = function () {
  68719. if (!_this._loadingDiv) {
  68720. return;
  68721. }
  68722. document.body.removeChild(_this._loadingDiv);
  68723. window.removeEventListener("resize", _this._resizeLoadingUI);
  68724. _this._loadingDiv = null;
  68725. };
  68726. this._loadingDiv.style.opacity = "0";
  68727. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  68728. };
  68729. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  68730. set: function (text) {
  68731. this._loadingText = text;
  68732. if (this._loadingTextDiv) {
  68733. this._loadingTextDiv.innerHTML = this._loadingText;
  68734. }
  68735. },
  68736. enumerable: true,
  68737. configurable: true
  68738. });
  68739. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  68740. get: function () {
  68741. return this._loadingDivBackgroundColor;
  68742. },
  68743. set: function (color) {
  68744. this._loadingDivBackgroundColor = color;
  68745. if (!this._loadingDiv) {
  68746. return;
  68747. }
  68748. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68749. },
  68750. enumerable: true,
  68751. configurable: true
  68752. });
  68753. return DefaultLoadingScreen;
  68754. }());
  68755. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  68756. })(BABYLON || (BABYLON = {}));
  68757. //# sourceMappingURL=babylon.loadingScreen.js.map
  68758. var BABYLON;
  68759. (function (BABYLON) {
  68760. var SceneLoaderProgressEvent = /** @class */ (function () {
  68761. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  68762. this.lengthComputable = lengthComputable;
  68763. this.loaded = loaded;
  68764. this.total = total;
  68765. }
  68766. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  68767. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  68768. };
  68769. return SceneLoaderProgressEvent;
  68770. }());
  68771. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  68772. var SceneLoader = /** @class */ (function () {
  68773. function SceneLoader() {
  68774. }
  68775. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  68776. get: function () {
  68777. return 0;
  68778. },
  68779. enumerable: true,
  68780. configurable: true
  68781. });
  68782. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  68783. get: function () {
  68784. return 1;
  68785. },
  68786. enumerable: true,
  68787. configurable: true
  68788. });
  68789. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  68790. get: function () {
  68791. return 2;
  68792. },
  68793. enumerable: true,
  68794. configurable: true
  68795. });
  68796. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  68797. get: function () {
  68798. return 3;
  68799. },
  68800. enumerable: true,
  68801. configurable: true
  68802. });
  68803. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  68804. get: function () {
  68805. return SceneLoader._ForceFullSceneLoadingForIncremental;
  68806. },
  68807. set: function (value) {
  68808. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  68809. },
  68810. enumerable: true,
  68811. configurable: true
  68812. });
  68813. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  68814. get: function () {
  68815. return SceneLoader._ShowLoadingScreen;
  68816. },
  68817. set: function (value) {
  68818. SceneLoader._ShowLoadingScreen = value;
  68819. },
  68820. enumerable: true,
  68821. configurable: true
  68822. });
  68823. Object.defineProperty(SceneLoader, "loggingLevel", {
  68824. get: function () {
  68825. return SceneLoader._loggingLevel;
  68826. },
  68827. set: function (value) {
  68828. SceneLoader._loggingLevel = value;
  68829. },
  68830. enumerable: true,
  68831. configurable: true
  68832. });
  68833. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  68834. get: function () {
  68835. return SceneLoader._CleanBoneMatrixWeights;
  68836. },
  68837. set: function (value) {
  68838. SceneLoader._CleanBoneMatrixWeights = value;
  68839. },
  68840. enumerable: true,
  68841. configurable: true
  68842. });
  68843. SceneLoader._getDefaultPlugin = function () {
  68844. return SceneLoader._registeredPlugins[".babylon"];
  68845. };
  68846. SceneLoader._getPluginForExtension = function (extension) {
  68847. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  68848. if (registeredPlugin) {
  68849. return registeredPlugin;
  68850. }
  68851. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  68852. return SceneLoader._getDefaultPlugin();
  68853. };
  68854. SceneLoader._getPluginForDirectLoad = function (data) {
  68855. for (var extension in SceneLoader._registeredPlugins) {
  68856. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  68857. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  68858. return SceneLoader._registeredPlugins[extension];
  68859. }
  68860. }
  68861. return SceneLoader._getDefaultPlugin();
  68862. };
  68863. SceneLoader._getPluginForFilename = function (sceneFilename) {
  68864. if (sceneFilename.name) {
  68865. sceneFilename = sceneFilename.name;
  68866. }
  68867. var queryStringPosition = sceneFilename.indexOf("?");
  68868. if (queryStringPosition !== -1) {
  68869. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  68870. }
  68871. var dotPosition = sceneFilename.lastIndexOf(".");
  68872. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  68873. return SceneLoader._getPluginForExtension(extension);
  68874. };
  68875. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  68876. SceneLoader._getDirectLoad = function (sceneFilename) {
  68877. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  68878. return sceneFilename.substr(5);
  68879. }
  68880. return null;
  68881. };
  68882. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  68883. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  68884. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  68885. var plugin;
  68886. if (registeredPlugin.plugin.createPlugin) {
  68887. plugin = registeredPlugin.plugin.createPlugin();
  68888. }
  68889. else {
  68890. plugin = registeredPlugin.plugin;
  68891. }
  68892. var useArrayBuffer = registeredPlugin.isBinary;
  68893. var database;
  68894. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  68895. var dataCallback = function (data, responseURL) {
  68896. if (scene.isDisposed) {
  68897. onError("Scene has been disposed");
  68898. return;
  68899. }
  68900. scene.database = database;
  68901. onSuccess(plugin, data, responseURL);
  68902. };
  68903. var request = null;
  68904. var pluginDisposed = false;
  68905. var onDisposeObservable = plugin.onDisposeObservable;
  68906. if (onDisposeObservable) {
  68907. onDisposeObservable.add(function () {
  68908. pluginDisposed = true;
  68909. if (request) {
  68910. request.abort();
  68911. request = null;
  68912. }
  68913. onDispose();
  68914. });
  68915. }
  68916. var manifestChecked = function () {
  68917. if (pluginDisposed) {
  68918. return;
  68919. }
  68920. var url = rootUrl + sceneFilename;
  68921. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  68922. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  68923. } : undefined, database, useArrayBuffer, function (request, exception) {
  68924. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  68925. });
  68926. };
  68927. if (directLoad) {
  68928. dataCallback(directLoad);
  68929. return plugin;
  68930. }
  68931. if (rootUrl.indexOf("file:") === -1) {
  68932. var engine = scene.getEngine();
  68933. var canUseOfflineSupport = engine.enableOfflineSupport;
  68934. if (canUseOfflineSupport) {
  68935. // Also check for exceptions
  68936. var exceptionFound = false;
  68937. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  68938. var regex = _a[_i];
  68939. if (regex.test(rootUrl + sceneFilename)) {
  68940. exceptionFound = true;
  68941. break;
  68942. }
  68943. }
  68944. canUseOfflineSupport = !exceptionFound;
  68945. }
  68946. if (canUseOfflineSupport) {
  68947. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  68948. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  68949. }
  68950. else {
  68951. manifestChecked();
  68952. }
  68953. }
  68954. // Loading file from disk via input file or drag'n'drop
  68955. else {
  68956. var fileOrString = sceneFilename;
  68957. if (fileOrString.name) { // File
  68958. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  68959. }
  68960. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  68961. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  68962. }
  68963. else {
  68964. onError("Unable to find file named " + sceneFilename);
  68965. }
  68966. }
  68967. return plugin;
  68968. };
  68969. // Public functions
  68970. SceneLoader.GetPluginForExtension = function (extension) {
  68971. return SceneLoader._getPluginForExtension(extension).plugin;
  68972. };
  68973. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  68974. return !!SceneLoader._registeredPlugins[extension];
  68975. };
  68976. SceneLoader.RegisterPlugin = function (plugin) {
  68977. if (typeof plugin.extensions === "string") {
  68978. var extension = plugin.extensions;
  68979. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  68980. plugin: plugin,
  68981. isBinary: false
  68982. };
  68983. }
  68984. else {
  68985. var extensions = plugin.extensions;
  68986. Object.keys(extensions).forEach(function (extension) {
  68987. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  68988. plugin: plugin,
  68989. isBinary: extensions[extension].isBinary
  68990. };
  68991. });
  68992. }
  68993. };
  68994. /**
  68995. * Import meshes into a scene
  68996. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  68997. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68998. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68999. * @param scene the instance of BABYLON.Scene to append to
  69000. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  69001. * @param onProgress a callback with a progress event for each file being loaded
  69002. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69003. * @param pluginExtension the extension used to determine the plugin
  69004. * @returns The loaded plugin
  69005. */
  69006. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69007. if (sceneFilename === void 0) { sceneFilename = ""; }
  69008. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69009. if (onSuccess === void 0) { onSuccess = null; }
  69010. if (onProgress === void 0) { onProgress = null; }
  69011. if (onError === void 0) { onError = null; }
  69012. if (pluginExtension === void 0) { pluginExtension = null; }
  69013. if (!scene) {
  69014. BABYLON.Tools.Error("No scene available to import mesh to");
  69015. return null;
  69016. }
  69017. if (!sceneFilename) {
  69018. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69019. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69020. }
  69021. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69022. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69023. return null;
  69024. }
  69025. var loadingToken = {};
  69026. scene._addPendingData(loadingToken);
  69027. var disposeHandler = function () {
  69028. scene._removePendingData(loadingToken);
  69029. };
  69030. var errorHandler = function (message, exception) {
  69031. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  69032. if (onError) {
  69033. onError(scene, errorMessage, exception);
  69034. }
  69035. else {
  69036. BABYLON.Tools.Error(errorMessage);
  69037. // should the exception be thrown?
  69038. }
  69039. disposeHandler();
  69040. };
  69041. var progressHandler = onProgress ? function (event) {
  69042. try {
  69043. onProgress(event);
  69044. }
  69045. catch (e) {
  69046. errorHandler("Error in onProgress callback", e);
  69047. }
  69048. } : undefined;
  69049. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  69050. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  69051. if (onSuccess) {
  69052. try {
  69053. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  69054. }
  69055. catch (e) {
  69056. errorHandler("Error in onSuccess callback", e);
  69057. }
  69058. }
  69059. scene._removePendingData(loadingToken);
  69060. };
  69061. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69062. if (plugin.rewriteRootURL) {
  69063. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  69064. }
  69065. if (sceneFilename === "") {
  69066. if (sceneFilename === "") {
  69067. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69068. }
  69069. }
  69070. if (plugin.importMesh) {
  69071. var syncedPlugin = plugin;
  69072. var meshes = new Array();
  69073. var particleSystems = new Array();
  69074. var skeletons = new Array();
  69075. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  69076. return;
  69077. }
  69078. scene.loadingPluginName = plugin.name;
  69079. successHandler(meshes, particleSystems, skeletons, []);
  69080. }
  69081. else {
  69082. var asyncedPlugin = plugin;
  69083. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  69084. scene.loadingPluginName = plugin.name;
  69085. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  69086. }).catch(function (error) {
  69087. errorHandler(error.message, error);
  69088. });
  69089. }
  69090. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69091. };
  69092. /**
  69093. * Import meshes into a scene
  69094. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69095. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69096. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69097. * @param scene the instance of BABYLON.Scene to append to
  69098. * @param onProgress a callback with a progress event for each file being loaded
  69099. * @param pluginExtension the extension used to determine the plugin
  69100. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  69101. */
  69102. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69103. if (sceneFilename === void 0) { sceneFilename = ""; }
  69104. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69105. if (onProgress === void 0) { onProgress = null; }
  69106. if (pluginExtension === void 0) { pluginExtension = null; }
  69107. return new Promise(function (resolve, reject) {
  69108. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  69109. resolve({
  69110. meshes: meshes,
  69111. particleSystems: particleSystems,
  69112. skeletons: skeletons,
  69113. animationGroups: animationGroups
  69114. });
  69115. }, onProgress, function (scene, message, exception) {
  69116. reject(exception || new Error(message));
  69117. }, pluginExtension);
  69118. });
  69119. };
  69120. /**
  69121. * Load a scene
  69122. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69123. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69124. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69125. * @param onSuccess a callback with the scene when import succeeds
  69126. * @param onProgress a callback with a progress event for each file being loaded
  69127. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69128. * @param pluginExtension the extension used to determine the plugin
  69129. * @returns The loaded plugin
  69130. */
  69131. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  69132. if (onSuccess === void 0) { onSuccess = null; }
  69133. if (onProgress === void 0) { onProgress = null; }
  69134. if (onError === void 0) { onError = null; }
  69135. if (pluginExtension === void 0) { pluginExtension = null; }
  69136. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  69137. };
  69138. /**
  69139. * Load a scene
  69140. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69141. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69142. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69143. * @param onProgress a callback with a progress event for each file being loaded
  69144. * @param pluginExtension the extension used to determine the plugin
  69145. * @returns The loaded scene
  69146. */
  69147. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  69148. if (onProgress === void 0) { onProgress = null; }
  69149. if (pluginExtension === void 0) { pluginExtension = null; }
  69150. return new Promise(function (resolve, reject) {
  69151. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  69152. resolve(scene);
  69153. }, onProgress, function (scene, message, exception) {
  69154. reject(exception || new Error(message));
  69155. }, pluginExtension);
  69156. });
  69157. };
  69158. /**
  69159. * Append a scene
  69160. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69161. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69162. * @param scene is the instance of BABYLON.Scene to append to
  69163. * @param onSuccess a callback with the scene when import succeeds
  69164. * @param onProgress a callback with a progress event for each file being loaded
  69165. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69166. * @param pluginExtension the extension used to determine the plugin
  69167. * @returns The loaded plugin
  69168. */
  69169. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69170. if (sceneFilename === void 0) { sceneFilename = ""; }
  69171. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69172. if (onSuccess === void 0) { onSuccess = null; }
  69173. if (onProgress === void 0) { onProgress = null; }
  69174. if (onError === void 0) { onError = null; }
  69175. if (pluginExtension === void 0) { pluginExtension = null; }
  69176. if (!scene) {
  69177. BABYLON.Tools.Error("No scene available to append to");
  69178. return null;
  69179. }
  69180. if (!sceneFilename) {
  69181. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69182. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69183. }
  69184. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69185. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69186. return null;
  69187. }
  69188. if (SceneLoader.ShowLoadingScreen) {
  69189. scene.getEngine().displayLoadingUI();
  69190. }
  69191. var loadingToken = {};
  69192. scene._addPendingData(loadingToken);
  69193. var disposeHandler = function () {
  69194. scene._removePendingData(loadingToken);
  69195. scene.getEngine().hideLoadingUI();
  69196. };
  69197. var errorHandler = function (message, exception) {
  69198. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69199. if (onError) {
  69200. onError(scene, errorMessage, exception);
  69201. }
  69202. else {
  69203. BABYLON.Tools.Error(errorMessage);
  69204. // should the exception be thrown?
  69205. }
  69206. disposeHandler();
  69207. };
  69208. var progressHandler = onProgress ? function (event) {
  69209. try {
  69210. onProgress(event);
  69211. }
  69212. catch (e) {
  69213. errorHandler("Error in onProgress callback", e);
  69214. }
  69215. } : undefined;
  69216. var successHandler = function () {
  69217. if (onSuccess) {
  69218. try {
  69219. onSuccess(scene);
  69220. }
  69221. catch (e) {
  69222. errorHandler("Error in onSuccess callback", e);
  69223. }
  69224. }
  69225. scene._removePendingData(loadingToken);
  69226. };
  69227. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69228. if (sceneFilename === "") {
  69229. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69230. }
  69231. if (plugin.load) {
  69232. var syncedPlugin = plugin;
  69233. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  69234. return;
  69235. }
  69236. scene.loadingPluginName = plugin.name;
  69237. successHandler();
  69238. }
  69239. else {
  69240. var asyncedPlugin = plugin;
  69241. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  69242. scene.loadingPluginName = plugin.name;
  69243. successHandler();
  69244. }).catch(function (error) {
  69245. errorHandler(error.message, error);
  69246. });
  69247. }
  69248. if (SceneLoader.ShowLoadingScreen) {
  69249. scene.executeWhenReady(function () {
  69250. scene.getEngine().hideLoadingUI();
  69251. });
  69252. }
  69253. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69254. };
  69255. /**
  69256. * Append a scene
  69257. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69258. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69259. * @param scene is the instance of BABYLON.Scene to append to
  69260. * @param onProgress a callback with a progress event for each file being loaded
  69261. * @param pluginExtension the extension used to determine the plugin
  69262. * @returns The given scene
  69263. */
  69264. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69265. if (sceneFilename === void 0) { sceneFilename = ""; }
  69266. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69267. if (onProgress === void 0) { onProgress = null; }
  69268. if (pluginExtension === void 0) { pluginExtension = null; }
  69269. return new Promise(function (resolve, reject) {
  69270. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  69271. resolve(scene);
  69272. }, onProgress, function (scene, message, exception) {
  69273. reject(exception || new Error(message));
  69274. }, pluginExtension);
  69275. });
  69276. };
  69277. /**
  69278. * Load a scene into an asset container
  69279. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69280. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69281. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  69282. * @param onSuccess a callback with the scene when import succeeds
  69283. * @param onProgress a callback with a progress event for each file being loaded
  69284. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69285. * @param pluginExtension the extension used to determine the plugin
  69286. * @returns The loaded plugin
  69287. */
  69288. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69289. if (sceneFilename === void 0) { sceneFilename = ""; }
  69290. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69291. if (onSuccess === void 0) { onSuccess = null; }
  69292. if (onProgress === void 0) { onProgress = null; }
  69293. if (onError === void 0) { onError = null; }
  69294. if (pluginExtension === void 0) { pluginExtension = null; }
  69295. if (!scene) {
  69296. BABYLON.Tools.Error("No scene available to load asset container to");
  69297. return null;
  69298. }
  69299. if (!sceneFilename) {
  69300. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69301. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69302. }
  69303. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69304. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69305. return null;
  69306. }
  69307. var loadingToken = {};
  69308. scene._addPendingData(loadingToken);
  69309. var disposeHandler = function () {
  69310. scene._removePendingData(loadingToken);
  69311. };
  69312. var errorHandler = function (message, exception) {
  69313. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69314. if (onError) {
  69315. onError(scene, errorMessage, exception);
  69316. }
  69317. else {
  69318. BABYLON.Tools.Error(errorMessage);
  69319. // should the exception be thrown?
  69320. }
  69321. disposeHandler();
  69322. };
  69323. var progressHandler = onProgress ? function (event) {
  69324. try {
  69325. onProgress(event);
  69326. }
  69327. catch (e) {
  69328. errorHandler("Error in onProgress callback", e);
  69329. }
  69330. } : undefined;
  69331. var successHandler = function (assets) {
  69332. if (onSuccess) {
  69333. try {
  69334. onSuccess(assets);
  69335. }
  69336. catch (e) {
  69337. errorHandler("Error in onSuccess callback", e);
  69338. }
  69339. }
  69340. scene._removePendingData(loadingToken);
  69341. };
  69342. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69343. if (plugin.loadAssetContainer) {
  69344. var syncedPlugin = plugin;
  69345. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  69346. if (!assetContainer) {
  69347. return;
  69348. }
  69349. scene.loadingPluginName = plugin.name;
  69350. successHandler(assetContainer);
  69351. }
  69352. else if (plugin.loadAssetContainerAsync) {
  69353. var asyncedPlugin = plugin;
  69354. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  69355. scene.loadingPluginName = plugin.name;
  69356. successHandler(assetContainer);
  69357. }).catch(function (error) {
  69358. errorHandler(error.message, error);
  69359. });
  69360. }
  69361. else {
  69362. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  69363. }
  69364. if (SceneLoader.ShowLoadingScreen) {
  69365. scene.executeWhenReady(function () {
  69366. scene.getEngine().hideLoadingUI();
  69367. });
  69368. }
  69369. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69370. };
  69371. /**
  69372. * Load a scene into an asset container
  69373. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69374. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69375. * @param scene is the instance of BABYLON.Scene to append to
  69376. * @param onProgress a callback with a progress event for each file being loaded
  69377. * @param pluginExtension the extension used to determine the plugin
  69378. * @returns The loaded asset container
  69379. */
  69380. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69381. if (sceneFilename === void 0) { sceneFilename = ""; }
  69382. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69383. if (onProgress === void 0) { onProgress = null; }
  69384. if (pluginExtension === void 0) { pluginExtension = null; }
  69385. return new Promise(function (resolve, reject) {
  69386. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  69387. resolve(assetContainer);
  69388. }, onProgress, function (scene, message, exception) {
  69389. reject(exception || new Error(message));
  69390. }, pluginExtension);
  69391. });
  69392. };
  69393. // Flags
  69394. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  69395. SceneLoader._ShowLoadingScreen = true;
  69396. SceneLoader._CleanBoneMatrixWeights = false;
  69397. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  69398. // Members
  69399. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  69400. SceneLoader._registeredPlugins = {};
  69401. return SceneLoader;
  69402. }());
  69403. BABYLON.SceneLoader = SceneLoader;
  69404. ;
  69405. })(BABYLON || (BABYLON = {}));
  69406. //# sourceMappingURL=babylon.sceneLoader.js.map
  69407. var BABYLON;
  69408. (function (BABYLON) {
  69409. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  69410. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69411. var parsedMaterial = parsedData.materials[index];
  69412. if (parsedMaterial.id === id) {
  69413. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69414. }
  69415. }
  69416. return null;
  69417. };
  69418. var isDescendantOf = function (mesh, names, hierarchyIds) {
  69419. for (var i in names) {
  69420. if (mesh.name === names[i]) {
  69421. hierarchyIds.push(mesh.id);
  69422. return true;
  69423. }
  69424. }
  69425. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  69426. hierarchyIds.push(mesh.id);
  69427. return true;
  69428. }
  69429. return false;
  69430. };
  69431. var logOperation = function (operation, producer) {
  69432. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  69433. };
  69434. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  69435. if (addToScene === void 0) { addToScene = false; }
  69436. var container = new BABYLON.AssetContainer(scene);
  69437. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69438. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69439. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69440. // and avoid problems with multiple concurrent .babylon loads.
  69441. var log = "importScene has failed JSON parse";
  69442. try {
  69443. var parsedData = JSON.parse(data);
  69444. log = "";
  69445. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69446. var index;
  69447. var cache;
  69448. // Lights
  69449. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  69450. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  69451. var parsedLight = parsedData.lights[index];
  69452. var light = BABYLON.Light.Parse(parsedLight, scene);
  69453. if (light) {
  69454. container.lights.push(light);
  69455. log += (index === 0 ? "\n\tLights:" : "");
  69456. log += "\n\t\t" + light.toString(fullDetails);
  69457. }
  69458. }
  69459. }
  69460. // Animations
  69461. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  69462. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  69463. var parsedAnimation = parsedData.animations[index];
  69464. var animation = BABYLON.Animation.Parse(parsedAnimation);
  69465. scene.animations.push(animation);
  69466. container.animations.push(animation);
  69467. log += (index === 0 ? "\n\tAnimations:" : "");
  69468. log += "\n\t\t" + animation.toString(fullDetails);
  69469. }
  69470. }
  69471. // Materials
  69472. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  69473. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69474. var parsedMaterial = parsedData.materials[index];
  69475. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69476. container.materials.push(mat);
  69477. log += (index === 0 ? "\n\tMaterials:" : "");
  69478. log += "\n\t\t" + mat.toString(fullDetails);
  69479. }
  69480. }
  69481. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69482. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  69483. var parsedMultiMaterial = parsedData.multiMaterials[index];
  69484. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69485. container.multiMaterials.push(mmat);
  69486. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  69487. log += "\n\t\t" + mmat.toString(fullDetails);
  69488. }
  69489. }
  69490. // Morph targets
  69491. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69492. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69493. var managerData = _a[_i];
  69494. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  69495. }
  69496. }
  69497. // Skeletons
  69498. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69499. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  69500. var parsedSkeleton = parsedData.skeletons[index];
  69501. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69502. container.skeletons.push(skeleton);
  69503. log += (index === 0 ? "\n\tSkeletons:" : "");
  69504. log += "\n\t\t" + skeleton.toString(fullDetails);
  69505. }
  69506. }
  69507. // Geometries
  69508. var geometries = parsedData.geometries;
  69509. if (geometries !== undefined && geometries !== null) {
  69510. var addedGeometry = new Array();
  69511. // Boxes
  69512. var boxes = geometries.boxes;
  69513. if (boxes !== undefined && boxes !== null) {
  69514. for (index = 0, cache = boxes.length; index < cache; index++) {
  69515. var parsedBox = boxes[index];
  69516. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  69517. }
  69518. }
  69519. // Spheres
  69520. var spheres = geometries.spheres;
  69521. if (spheres !== undefined && spheres !== null) {
  69522. for (index = 0, cache = spheres.length; index < cache; index++) {
  69523. var parsedSphere = spheres[index];
  69524. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  69525. }
  69526. }
  69527. // Cylinders
  69528. var cylinders = geometries.cylinders;
  69529. if (cylinders !== undefined && cylinders !== null) {
  69530. for (index = 0, cache = cylinders.length; index < cache; index++) {
  69531. var parsedCylinder = cylinders[index];
  69532. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  69533. }
  69534. }
  69535. // Toruses
  69536. var toruses = geometries.toruses;
  69537. if (toruses !== undefined && toruses !== null) {
  69538. for (index = 0, cache = toruses.length; index < cache; index++) {
  69539. var parsedTorus = toruses[index];
  69540. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  69541. }
  69542. }
  69543. // Grounds
  69544. var grounds = geometries.grounds;
  69545. if (grounds !== undefined && grounds !== null) {
  69546. for (index = 0, cache = grounds.length; index < cache; index++) {
  69547. var parsedGround = grounds[index];
  69548. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  69549. }
  69550. }
  69551. // Planes
  69552. var planes = geometries.planes;
  69553. if (planes !== undefined && planes !== null) {
  69554. for (index = 0, cache = planes.length; index < cache; index++) {
  69555. var parsedPlane = planes[index];
  69556. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  69557. }
  69558. }
  69559. // TorusKnots
  69560. var torusKnots = geometries.torusKnots;
  69561. if (torusKnots !== undefined && torusKnots !== null) {
  69562. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  69563. var parsedTorusKnot = torusKnots[index];
  69564. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  69565. }
  69566. }
  69567. // VertexData
  69568. var vertexData = geometries.vertexData;
  69569. if (vertexData !== undefined && vertexData !== null) {
  69570. for (index = 0, cache = vertexData.length; index < cache; index++) {
  69571. var parsedVertexData = vertexData[index];
  69572. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  69573. }
  69574. }
  69575. addedGeometry.forEach(function (g) {
  69576. if (g) {
  69577. container.geometries.push(g);
  69578. }
  69579. });
  69580. }
  69581. // Transform nodes
  69582. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  69583. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  69584. var parsedTransformNode = parsedData.transformNodes[index];
  69585. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  69586. container.transformNodes.push(node);
  69587. }
  69588. }
  69589. // Meshes
  69590. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69591. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69592. var parsedMesh = parsedData.meshes[index];
  69593. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69594. container.meshes.push(mesh);
  69595. log += (index === 0 ? "\n\tMeshes:" : "");
  69596. log += "\n\t\t" + mesh.toString(fullDetails);
  69597. }
  69598. }
  69599. // Cameras
  69600. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  69601. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  69602. var parsedCamera = parsedData.cameras[index];
  69603. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  69604. container.cameras.push(camera);
  69605. log += (index === 0 ? "\n\tCameras:" : "");
  69606. log += "\n\t\t" + camera.toString(fullDetails);
  69607. }
  69608. }
  69609. // Browsing all the graph to connect the dots
  69610. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  69611. var camera = scene.cameras[index];
  69612. if (camera._waitingParentId) {
  69613. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  69614. camera._waitingParentId = null;
  69615. }
  69616. }
  69617. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69618. var light_1 = scene.lights[index];
  69619. if (light_1 && light_1._waitingParentId) {
  69620. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  69621. light_1._waitingParentId = null;
  69622. }
  69623. }
  69624. // Sounds
  69625. // TODO: add sound
  69626. var loadedSounds = [];
  69627. var loadedSound;
  69628. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69629. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69630. var parsedSound = parsedData.sounds[index];
  69631. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69632. if (!parsedSound.url)
  69633. parsedSound.url = parsedSound.name;
  69634. if (!loadedSounds[parsedSound.url]) {
  69635. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69636. loadedSounds[parsedSound.url] = loadedSound;
  69637. container.sounds.push(loadedSound);
  69638. }
  69639. else {
  69640. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69641. }
  69642. }
  69643. else {
  69644. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69645. }
  69646. }
  69647. }
  69648. loadedSounds = [];
  69649. // Connect parents & children and parse actions
  69650. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  69651. var transformNode = scene.transformNodes[index];
  69652. if (transformNode._waitingParentId) {
  69653. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  69654. transformNode._waitingParentId = null;
  69655. }
  69656. }
  69657. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69658. var mesh = scene.meshes[index];
  69659. if (mesh._waitingParentId) {
  69660. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  69661. mesh._waitingParentId = null;
  69662. }
  69663. if (mesh._waitingActions) {
  69664. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  69665. mesh._waitingActions = null;
  69666. }
  69667. }
  69668. // freeze world matrix application
  69669. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69670. var currentMesh = scene.meshes[index];
  69671. if (currentMesh._waitingFreezeWorldMatrix) {
  69672. currentMesh.freezeWorldMatrix();
  69673. currentMesh._waitingFreezeWorldMatrix = null;
  69674. }
  69675. else {
  69676. currentMesh.computeWorldMatrix(true);
  69677. }
  69678. }
  69679. // Shadows
  69680. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  69681. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  69682. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  69683. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  69684. // SG would be available on their associated lights
  69685. }
  69686. }
  69687. // Lights exclusions / inclusions
  69688. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69689. var light_2 = scene.lights[index];
  69690. // Excluded check
  69691. if (light_2._excludedMeshesIds.length > 0) {
  69692. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  69693. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  69694. if (excludedMesh) {
  69695. light_2.excludedMeshes.push(excludedMesh);
  69696. }
  69697. }
  69698. light_2._excludedMeshesIds = [];
  69699. }
  69700. // Included check
  69701. if (light_2._includedOnlyMeshesIds.length > 0) {
  69702. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  69703. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  69704. if (includedOnlyMesh) {
  69705. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  69706. }
  69707. }
  69708. light_2._includedOnlyMeshesIds = [];
  69709. }
  69710. }
  69711. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  69712. // Actions (scene)
  69713. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  69714. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  69715. }
  69716. if (!addToScene) {
  69717. container.removeAllFromScene();
  69718. }
  69719. }
  69720. catch (err) {
  69721. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  69722. if (onError) {
  69723. onError(msg, err);
  69724. }
  69725. else {
  69726. BABYLON.Tools.Log(msg);
  69727. throw err;
  69728. }
  69729. }
  69730. finally {
  69731. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69732. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69733. }
  69734. }
  69735. return container;
  69736. };
  69737. BABYLON.SceneLoader.RegisterPlugin({
  69738. name: "babylon.js",
  69739. extensions: ".babylon",
  69740. canDirectLoad: function (data) {
  69741. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  69742. return true;
  69743. }
  69744. return false;
  69745. },
  69746. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  69747. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69748. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69749. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69750. // and avoid problems with multiple concurrent .babylon loads.
  69751. var log = "importMesh has failed JSON parse";
  69752. try {
  69753. var parsedData = JSON.parse(data);
  69754. log = "";
  69755. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69756. if (!meshesNames) {
  69757. meshesNames = null;
  69758. }
  69759. else if (!Array.isArray(meshesNames)) {
  69760. meshesNames = [meshesNames];
  69761. }
  69762. var hierarchyIds = new Array();
  69763. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69764. var loadedSkeletonsIds = [];
  69765. var loadedMaterialsIds = [];
  69766. var index;
  69767. var cache;
  69768. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69769. var parsedMesh = parsedData.meshes[index];
  69770. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  69771. if (meshesNames !== null) {
  69772. // Remove found mesh name from list.
  69773. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  69774. }
  69775. //Geometry?
  69776. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  69777. //does the file contain geometries?
  69778. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  69779. //find the correct geometry and add it to the scene
  69780. var found = false;
  69781. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  69782. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  69783. return;
  69784. }
  69785. else {
  69786. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  69787. if (parsedGeometryData.id === parsedMesh.geometryId) {
  69788. switch (geometryType) {
  69789. case "boxes":
  69790. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  69791. break;
  69792. case "spheres":
  69793. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  69794. break;
  69795. case "cylinders":
  69796. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  69797. break;
  69798. case "toruses":
  69799. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  69800. break;
  69801. case "grounds":
  69802. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  69803. break;
  69804. case "planes":
  69805. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  69806. break;
  69807. case "torusKnots":
  69808. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  69809. break;
  69810. case "vertexData":
  69811. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  69812. break;
  69813. }
  69814. found = true;
  69815. }
  69816. });
  69817. }
  69818. });
  69819. if (found === false) {
  69820. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  69821. }
  69822. }
  69823. }
  69824. // Material ?
  69825. if (parsedMesh.materialId) {
  69826. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  69827. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69828. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  69829. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  69830. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  69831. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  69832. var subMatId = parsedMultiMaterial.materials[matIndex];
  69833. loadedMaterialsIds.push(subMatId);
  69834. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  69835. if (mat) {
  69836. log += "\n\tMaterial " + mat.toString(fullDetails);
  69837. }
  69838. }
  69839. loadedMaterialsIds.push(parsedMultiMaterial.id);
  69840. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69841. if (mmat) {
  69842. materialFound = true;
  69843. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  69844. }
  69845. break;
  69846. }
  69847. }
  69848. }
  69849. if (materialFound === false) {
  69850. loadedMaterialsIds.push(parsedMesh.materialId);
  69851. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  69852. if (!mat) {
  69853. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  69854. }
  69855. else {
  69856. log += "\n\tMaterial " + mat.toString(fullDetails);
  69857. }
  69858. }
  69859. }
  69860. // Skeleton ?
  69861. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69862. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  69863. if (skeletonAlreadyLoaded === false) {
  69864. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  69865. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  69866. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  69867. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69868. skeletons.push(skeleton);
  69869. loadedSkeletonsIds.push(parsedSkeleton.id);
  69870. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  69871. }
  69872. }
  69873. }
  69874. }
  69875. // Morph targets ?
  69876. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69877. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69878. var managerData = _a[_i];
  69879. BABYLON.MorphTargetManager.Parse(managerData, scene);
  69880. }
  69881. }
  69882. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69883. meshes.push(mesh);
  69884. log += "\n\tMesh " + mesh.toString(fullDetails);
  69885. }
  69886. }
  69887. // Connecting parents
  69888. var currentMesh;
  69889. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69890. currentMesh = scene.meshes[index];
  69891. if (currentMesh._waitingParentId) {
  69892. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  69893. currentMesh._waitingParentId = null;
  69894. }
  69895. }
  69896. // freeze and compute world matrix application
  69897. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69898. currentMesh = scene.meshes[index];
  69899. if (currentMesh._waitingFreezeWorldMatrix) {
  69900. currentMesh.freezeWorldMatrix();
  69901. currentMesh._waitingFreezeWorldMatrix = null;
  69902. }
  69903. else {
  69904. currentMesh.computeWorldMatrix(true);
  69905. }
  69906. }
  69907. }
  69908. // Particles
  69909. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  69910. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  69911. if (parser) {
  69912. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  69913. var parsedParticleSystem = parsedData.particleSystems[index];
  69914. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  69915. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  69916. }
  69917. }
  69918. }
  69919. }
  69920. return true;
  69921. }
  69922. catch (err) {
  69923. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  69924. if (onError) {
  69925. onError(msg, err);
  69926. }
  69927. else {
  69928. BABYLON.Tools.Log(msg);
  69929. throw err;
  69930. }
  69931. }
  69932. finally {
  69933. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69934. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69935. }
  69936. }
  69937. return false;
  69938. },
  69939. load: function (scene, data, rootUrl, onError) {
  69940. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69941. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69942. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69943. // and avoid problems with multiple concurrent .babylon loads.
  69944. var log = "importScene has failed JSON parse";
  69945. try {
  69946. var parsedData = JSON.parse(data);
  69947. log = "";
  69948. // Scene
  69949. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  69950. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  69951. }
  69952. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  69953. scene.autoClear = parsedData.autoClear;
  69954. }
  69955. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  69956. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  69957. }
  69958. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  69959. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  69960. }
  69961. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  69962. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  69963. }
  69964. // Fog
  69965. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  69966. scene.fogMode = parsedData.fogMode;
  69967. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  69968. scene.fogStart = parsedData.fogStart;
  69969. scene.fogEnd = parsedData.fogEnd;
  69970. scene.fogDensity = parsedData.fogDensity;
  69971. log += "\tFog mode for scene: ";
  69972. switch (scene.fogMode) {
  69973. // getters not compiling, so using hardcoded
  69974. case 1:
  69975. log += "exp\n";
  69976. break;
  69977. case 2:
  69978. log += "exp2\n";
  69979. break;
  69980. case 3:
  69981. log += "linear\n";
  69982. break;
  69983. }
  69984. }
  69985. //Physics
  69986. if (parsedData.physicsEnabled) {
  69987. var physicsPlugin;
  69988. if (parsedData.physicsEngine === "cannon") {
  69989. physicsPlugin = new BABYLON.CannonJSPlugin();
  69990. }
  69991. else if (parsedData.physicsEngine === "oimo") {
  69992. physicsPlugin = new BABYLON.OimoJSPlugin();
  69993. }
  69994. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  69995. //else - default engine, which is currently oimo
  69996. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  69997. scene.enablePhysics(physicsGravity, physicsPlugin);
  69998. }
  69999. // Metadata
  70000. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  70001. scene.metadata = parsedData.metadata;
  70002. }
  70003. //collisions, if defined. otherwise, default is true
  70004. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  70005. scene.collisionsEnabled = parsedData.collisionsEnabled;
  70006. }
  70007. scene.workerCollisions = !!parsedData.workerCollisions;
  70008. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  70009. if (!container) {
  70010. return false;
  70011. }
  70012. if (parsedData.autoAnimate) {
  70013. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  70014. }
  70015. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  70016. scene.setActiveCameraByID(parsedData.activeCameraID);
  70017. }
  70018. // Environment texture
  70019. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  70020. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  70021. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  70022. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  70023. if (parsedData.environmentTextureRotationY) {
  70024. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  70025. }
  70026. scene.environmentTexture = hdrTexture;
  70027. }
  70028. else {
  70029. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  70030. if (parsedData.environmentTextureRotationY) {
  70031. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  70032. }
  70033. scene.environmentTexture = cubeTexture;
  70034. }
  70035. if (parsedData.createDefaultSkybox === true) {
  70036. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  70037. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  70038. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  70039. }
  70040. }
  70041. // Finish
  70042. return true;
  70043. }
  70044. catch (err) {
  70045. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  70046. if (onError) {
  70047. onError(msg, err);
  70048. }
  70049. else {
  70050. BABYLON.Tools.Log(msg);
  70051. throw err;
  70052. }
  70053. }
  70054. finally {
  70055. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70056. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70057. }
  70058. }
  70059. return false;
  70060. },
  70061. loadAssetContainer: function (scene, data, rootUrl, onError) {
  70062. var container = loadAssetContainer(scene, data, rootUrl, onError);
  70063. return container;
  70064. }
  70065. });
  70066. })(BABYLON || (BABYLON = {}));
  70067. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  70068. var BABYLON;
  70069. (function (BABYLON) {
  70070. var FilesInput = /** @class */ (function () {
  70071. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  70072. this.onProcessFileCallback = function () { return true; };
  70073. this._engine = engine;
  70074. this._currentScene = scene;
  70075. this._sceneLoadedCallback = sceneLoadedCallback;
  70076. this._progressCallback = progressCallback;
  70077. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  70078. this._textureLoadingCallback = textureLoadingCallback;
  70079. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  70080. this._onReloadCallback = onReloadCallback;
  70081. this._errorCallback = errorCallback;
  70082. }
  70083. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  70084. var _this = this;
  70085. if (elementToMonitor) {
  70086. this._elementToMonitor = elementToMonitor;
  70087. this._dragEnterHandler = function (e) { _this.drag(e); };
  70088. this._dragOverHandler = function (e) { _this.drag(e); };
  70089. this._dropHandler = function (e) { _this.drop(e); };
  70090. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  70091. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  70092. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  70093. }
  70094. };
  70095. FilesInput.prototype.dispose = function () {
  70096. if (!this._elementToMonitor) {
  70097. return;
  70098. }
  70099. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  70100. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  70101. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  70102. };
  70103. FilesInput.prototype.renderFunction = function () {
  70104. if (this._additionalRenderLoopLogicCallback) {
  70105. this._additionalRenderLoopLogicCallback();
  70106. }
  70107. if (this._currentScene) {
  70108. if (this._textureLoadingCallback) {
  70109. var remaining = this._currentScene.getWaitingItemsCount();
  70110. if (remaining > 0) {
  70111. this._textureLoadingCallback(remaining);
  70112. }
  70113. }
  70114. this._currentScene.render();
  70115. }
  70116. };
  70117. FilesInput.prototype.drag = function (e) {
  70118. e.stopPropagation();
  70119. e.preventDefault();
  70120. };
  70121. FilesInput.prototype.drop = function (eventDrop) {
  70122. eventDrop.stopPropagation();
  70123. eventDrop.preventDefault();
  70124. this.loadFiles(eventDrop);
  70125. };
  70126. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  70127. var _this = this;
  70128. var reader = folder.createReader();
  70129. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  70130. reader.readEntries(function (entries) {
  70131. remaining.count += entries.length;
  70132. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  70133. var entry = entries_1[_i];
  70134. if (entry.isFile) {
  70135. entry.file(function (file) {
  70136. file.correctName = relativePath + file.name;
  70137. files.push(file);
  70138. if (--remaining.count === 0) {
  70139. callback();
  70140. }
  70141. });
  70142. }
  70143. else if (entry.isDirectory) {
  70144. _this._traverseFolder(entry, files, remaining, callback);
  70145. }
  70146. }
  70147. if (--remaining.count) {
  70148. callback();
  70149. }
  70150. });
  70151. };
  70152. FilesInput.prototype._processFiles = function (files) {
  70153. for (var i = 0; i < files.length; i++) {
  70154. var name = files[i].correctName.toLowerCase();
  70155. var extension = name.split('.').pop();
  70156. if (!this.onProcessFileCallback(files[i], name, extension)) {
  70157. continue;
  70158. }
  70159. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  70160. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  70161. this._sceneFileToLoad = files[i];
  70162. }
  70163. else {
  70164. FilesInput.FilesToLoad[name] = files[i];
  70165. }
  70166. }
  70167. };
  70168. FilesInput.prototype.loadFiles = function (event) {
  70169. var _this = this;
  70170. if (this._startingProcessingFilesCallback)
  70171. this._startingProcessingFilesCallback();
  70172. // Handling data transfer via drag'n'drop
  70173. if (event && event.dataTransfer && event.dataTransfer.files) {
  70174. this._filesToLoad = event.dataTransfer.files;
  70175. }
  70176. // Handling files from input files
  70177. if (event && event.target && event.target.files) {
  70178. this._filesToLoad = event.target.files;
  70179. }
  70180. if (this._filesToLoad && this._filesToLoad.length > 0) {
  70181. var files_1 = new Array();
  70182. var folders = [];
  70183. var items = event.dataTransfer ? event.dataTransfer.items : null;
  70184. for (var i = 0; i < this._filesToLoad.length; i++) {
  70185. var fileToLoad = this._filesToLoad[i];
  70186. var name_1 = fileToLoad.name.toLowerCase();
  70187. var entry = void 0;
  70188. fileToLoad.correctName = name_1;
  70189. if (items) {
  70190. var item = items[i];
  70191. if (item.getAsEntry) {
  70192. entry = item.getAsEntry();
  70193. }
  70194. else if (item.webkitGetAsEntry) {
  70195. entry = item.webkitGetAsEntry();
  70196. }
  70197. }
  70198. if (!entry) {
  70199. files_1.push(fileToLoad);
  70200. }
  70201. else {
  70202. if (entry.isDirectory) {
  70203. folders.push(entry);
  70204. }
  70205. else {
  70206. files_1.push(fileToLoad);
  70207. }
  70208. }
  70209. }
  70210. if (folders.length === 0) {
  70211. this._processFiles(files_1);
  70212. this._processReload();
  70213. }
  70214. else {
  70215. var remaining = { count: folders.length };
  70216. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  70217. var folder = folders_1[_i];
  70218. this._traverseFolder(folder, files_1, remaining, function () {
  70219. _this._processFiles(files_1);
  70220. if (remaining.count === 0) {
  70221. _this._processReload();
  70222. }
  70223. });
  70224. }
  70225. }
  70226. }
  70227. };
  70228. FilesInput.prototype._processReload = function () {
  70229. if (this._onReloadCallback) {
  70230. this._onReloadCallback(this._sceneFileToLoad);
  70231. }
  70232. else {
  70233. this.reload();
  70234. }
  70235. };
  70236. FilesInput.prototype.reload = function () {
  70237. var _this = this;
  70238. // If a scene file has been provided
  70239. if (this._sceneFileToLoad) {
  70240. if (this._currentScene) {
  70241. if (BABYLON.Tools.errorsCount > 0) {
  70242. BABYLON.Tools.ClearLogCache();
  70243. }
  70244. this._engine.stopRenderLoop();
  70245. }
  70246. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  70247. if (_this._progressCallback) {
  70248. _this._progressCallback(progress);
  70249. }
  70250. }).then(function (scene) {
  70251. if (_this._currentScene) {
  70252. _this._currentScene.dispose();
  70253. }
  70254. _this._currentScene = scene;
  70255. if (_this._sceneLoadedCallback) {
  70256. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  70257. }
  70258. // Wait for textures and shaders to be ready
  70259. _this._currentScene.executeWhenReady(function () {
  70260. _this._engine.runRenderLoop(function () {
  70261. _this.renderFunction();
  70262. });
  70263. });
  70264. }).catch(function (error) {
  70265. if (_this._errorCallback) {
  70266. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  70267. }
  70268. });
  70269. }
  70270. else {
  70271. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  70272. }
  70273. };
  70274. FilesInput.FilesToLoad = {};
  70275. return FilesInput;
  70276. }());
  70277. BABYLON.FilesInput = FilesInput;
  70278. })(BABYLON || (BABYLON = {}));
  70279. //# sourceMappingURL=babylon.filesInput.js.map
  70280. var BABYLON;
  70281. (function (BABYLON) {
  70282. var Tags = /** @class */ (function () {
  70283. function Tags() {
  70284. }
  70285. Tags.EnableFor = function (obj) {
  70286. obj._tags = obj._tags || {};
  70287. obj.hasTags = function () {
  70288. return Tags.HasTags(obj);
  70289. };
  70290. obj.addTags = function (tagsString) {
  70291. return Tags.AddTagsTo(obj, tagsString);
  70292. };
  70293. obj.removeTags = function (tagsString) {
  70294. return Tags.RemoveTagsFrom(obj, tagsString);
  70295. };
  70296. obj.matchesTagsQuery = function (tagsQuery) {
  70297. return Tags.MatchesQuery(obj, tagsQuery);
  70298. };
  70299. };
  70300. Tags.DisableFor = function (obj) {
  70301. delete obj._tags;
  70302. delete obj.hasTags;
  70303. delete obj.addTags;
  70304. delete obj.removeTags;
  70305. delete obj.matchesTagsQuery;
  70306. };
  70307. Tags.HasTags = function (obj) {
  70308. if (!obj._tags) {
  70309. return false;
  70310. }
  70311. return !BABYLON.Tools.IsEmpty(obj._tags);
  70312. };
  70313. Tags.GetTags = function (obj, asString) {
  70314. if (asString === void 0) { asString = true; }
  70315. if (!obj._tags) {
  70316. return null;
  70317. }
  70318. if (asString) {
  70319. var tagsArray = [];
  70320. for (var tag in obj._tags) {
  70321. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  70322. tagsArray.push(tag);
  70323. }
  70324. }
  70325. return tagsArray.join(" ");
  70326. }
  70327. else {
  70328. return obj._tags;
  70329. }
  70330. };
  70331. // the tags 'true' and 'false' are reserved and cannot be used as tags
  70332. // a tag cannot start with '||', '&&', and '!'
  70333. // it cannot contain whitespaces
  70334. Tags.AddTagsTo = function (obj, tagsString) {
  70335. if (!tagsString) {
  70336. return;
  70337. }
  70338. if (typeof tagsString !== "string") {
  70339. return;
  70340. }
  70341. var tags = tagsString.split(" ");
  70342. tags.forEach(function (tag, index, array) {
  70343. Tags._AddTagTo(obj, tag);
  70344. });
  70345. };
  70346. Tags._AddTagTo = function (obj, tag) {
  70347. tag = tag.trim();
  70348. if (tag === "" || tag === "true" || tag === "false") {
  70349. return;
  70350. }
  70351. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  70352. return;
  70353. }
  70354. Tags.EnableFor(obj);
  70355. obj._tags[tag] = true;
  70356. };
  70357. Tags.RemoveTagsFrom = function (obj, tagsString) {
  70358. if (!Tags.HasTags(obj)) {
  70359. return;
  70360. }
  70361. var tags = tagsString.split(" ");
  70362. for (var t in tags) {
  70363. Tags._RemoveTagFrom(obj, tags[t]);
  70364. }
  70365. };
  70366. Tags._RemoveTagFrom = function (obj, tag) {
  70367. delete obj._tags[tag];
  70368. };
  70369. Tags.MatchesQuery = function (obj, tagsQuery) {
  70370. if (tagsQuery === undefined) {
  70371. return true;
  70372. }
  70373. if (tagsQuery === "") {
  70374. return Tags.HasTags(obj);
  70375. }
  70376. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  70377. };
  70378. return Tags;
  70379. }());
  70380. BABYLON.Tags = Tags;
  70381. })(BABYLON || (BABYLON = {}));
  70382. //# sourceMappingURL=babylon.tags.js.map
  70383. var BABYLON;
  70384. (function (BABYLON) {
  70385. /**
  70386. * Class used to evalaute queries containing `and` and `or` operators
  70387. */
  70388. var AndOrNotEvaluator = /** @class */ (function () {
  70389. function AndOrNotEvaluator() {
  70390. }
  70391. /**
  70392. * Evaluate a query
  70393. * @param query defines the query to evaluate
  70394. * @param evaluateCallback defines the callback used to filter result
  70395. * @returns true if the query matches
  70396. */
  70397. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  70398. if (!query.match(/\([^\(\)]*\)/g)) {
  70399. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  70400. }
  70401. else {
  70402. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  70403. // remove parenthesis
  70404. r = r.slice(1, r.length - 1);
  70405. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  70406. });
  70407. }
  70408. if (query === "true") {
  70409. return true;
  70410. }
  70411. if (query === "false") {
  70412. return false;
  70413. }
  70414. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  70415. };
  70416. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  70417. evaluateCallback = evaluateCallback || (function (r) {
  70418. return r === "true" ? true : false;
  70419. });
  70420. var result;
  70421. var or = parenthesisContent.split("||");
  70422. for (var i in or) {
  70423. if (or.hasOwnProperty(i)) {
  70424. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  70425. var and = ori.split("&&");
  70426. if (and.length > 1) {
  70427. for (var j = 0; j < and.length; ++j) {
  70428. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  70429. if (andj !== "true" && andj !== "false") {
  70430. if (andj[0] === "!") {
  70431. result = !evaluateCallback(andj.substring(1));
  70432. }
  70433. else {
  70434. result = evaluateCallback(andj);
  70435. }
  70436. }
  70437. else {
  70438. result = andj === "true" ? true : false;
  70439. }
  70440. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  70441. ori = "false";
  70442. break;
  70443. }
  70444. }
  70445. }
  70446. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  70447. result = true;
  70448. break;
  70449. }
  70450. // result equals false (or undefined)
  70451. if (ori !== "true" && ori !== "false") {
  70452. if (ori[0] === "!") {
  70453. result = !evaluateCallback(ori.substring(1));
  70454. }
  70455. else {
  70456. result = evaluateCallback(ori);
  70457. }
  70458. }
  70459. else {
  70460. result = ori === "true" ? true : false;
  70461. }
  70462. }
  70463. }
  70464. // the whole parenthesis scope is replaced by 'true' or 'false'
  70465. return result ? "true" : "false";
  70466. };
  70467. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  70468. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  70469. // remove whitespaces
  70470. r = r.replace(/[\s]/g, function () { return ""; });
  70471. return r.length % 2 ? "!" : "";
  70472. });
  70473. booleanString = booleanString.trim();
  70474. if (booleanString === "!true") {
  70475. booleanString = "false";
  70476. }
  70477. else if (booleanString === "!false") {
  70478. booleanString = "true";
  70479. }
  70480. return booleanString;
  70481. };
  70482. return AndOrNotEvaluator;
  70483. }());
  70484. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  70485. })(BABYLON || (BABYLON = {}));
  70486. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  70487. var BABYLON;
  70488. (function (BABYLON) {
  70489. /**
  70490. * Class used to enable access to IndexedDB
  70491. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  70492. */
  70493. var Database = /** @class */ (function () {
  70494. /**
  70495. * Creates a new Database
  70496. * @param urlToScene defines the url to load the scene
  70497. * @param callbackManifestChecked defines the callback to use when manifest is checked
  70498. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  70499. */
  70500. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  70501. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  70502. var _this = this;
  70503. // Handling various flavors of prefixed version of IndexedDB
  70504. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  70505. this.callbackManifestChecked = callbackManifestChecked;
  70506. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  70507. this.db = null;
  70508. this._enableSceneOffline = false;
  70509. this._enableTexturesOffline = false;
  70510. this.manifestVersionFound = 0;
  70511. this.mustUpdateRessources = false;
  70512. this.hasReachedQuota = false;
  70513. if (!Database.IDBStorageEnabled) {
  70514. this.callbackManifestChecked(true);
  70515. }
  70516. else {
  70517. if (disableManifestCheck) {
  70518. this._enableSceneOffline = true;
  70519. this._enableTexturesOffline = true;
  70520. this.manifestVersionFound = 1;
  70521. BABYLON.Tools.SetImmediate(function () {
  70522. _this.callbackManifestChecked(true);
  70523. });
  70524. }
  70525. else {
  70526. this._checkManifestFile();
  70527. }
  70528. }
  70529. }
  70530. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  70531. /**
  70532. * Gets a boolean indicating if scene must be saved in the database
  70533. */
  70534. get: function () {
  70535. return this._enableSceneOffline;
  70536. },
  70537. enumerable: true,
  70538. configurable: true
  70539. });
  70540. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  70541. /**
  70542. * Gets a boolean indicating if textures must be saved in the database
  70543. */
  70544. get: function () {
  70545. return this._enableTexturesOffline;
  70546. },
  70547. enumerable: true,
  70548. configurable: true
  70549. });
  70550. Database.prototype._checkManifestFile = function () {
  70551. var _this = this;
  70552. var noManifestFile = function () {
  70553. _this._enableSceneOffline = false;
  70554. _this._enableTexturesOffline = false;
  70555. _this.callbackManifestChecked(false);
  70556. };
  70557. var timeStampUsed = false;
  70558. var manifestURL = this.currentSceneUrl + ".manifest";
  70559. var xhr = new XMLHttpRequest();
  70560. if (navigator.onLine) {
  70561. // Adding a timestamp to by-pass browsers' cache
  70562. timeStampUsed = true;
  70563. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  70564. }
  70565. xhr.open("GET", manifestURL, true);
  70566. xhr.addEventListener("load", function () {
  70567. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70568. try {
  70569. var manifestFile = JSON.parse(xhr.response);
  70570. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  70571. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  70572. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  70573. _this.manifestVersionFound = manifestFile.version;
  70574. }
  70575. if (_this.callbackManifestChecked) {
  70576. _this.callbackManifestChecked(true);
  70577. }
  70578. }
  70579. catch (ex) {
  70580. noManifestFile();
  70581. }
  70582. }
  70583. else {
  70584. noManifestFile();
  70585. }
  70586. }, false);
  70587. xhr.addEventListener("error", function (event) {
  70588. if (timeStampUsed) {
  70589. timeStampUsed = false;
  70590. // Let's retry without the timeStamp
  70591. // It could fail when coupled with HTML5 Offline API
  70592. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  70593. xhr.open("GET", retryManifestURL, true);
  70594. xhr.send();
  70595. }
  70596. else {
  70597. noManifestFile();
  70598. }
  70599. }, false);
  70600. try {
  70601. xhr.send();
  70602. }
  70603. catch (ex) {
  70604. BABYLON.Tools.Error("Error on XHR send request.");
  70605. this.callbackManifestChecked(false);
  70606. }
  70607. };
  70608. /**
  70609. * Open the database and make it available
  70610. * @param successCallback defines the callback to call on success
  70611. * @param errorCallback defines the callback to call on error
  70612. */
  70613. Database.prototype.openAsync = function (successCallback, errorCallback) {
  70614. var _this = this;
  70615. var handleError = function () {
  70616. _this.isSupported = false;
  70617. if (errorCallback)
  70618. errorCallback();
  70619. };
  70620. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  70621. // Your browser doesn't support IndexedDB
  70622. this.isSupported = false;
  70623. if (errorCallback)
  70624. errorCallback();
  70625. }
  70626. else {
  70627. // If the DB hasn't been opened or created yet
  70628. if (!this.db) {
  70629. this.hasReachedQuota = false;
  70630. this.isSupported = true;
  70631. var request = this.idbFactory.open("babylonjs", 1);
  70632. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  70633. request.onerror = function (event) {
  70634. handleError();
  70635. };
  70636. // executes when a version change transaction cannot complete due to other active transactions
  70637. request.onblocked = function (event) {
  70638. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  70639. handleError();
  70640. };
  70641. // DB has been opened successfully
  70642. request.onsuccess = function (event) {
  70643. _this.db = request.result;
  70644. successCallback();
  70645. };
  70646. // Initialization of the DB. Creating Scenes & Textures stores
  70647. request.onupgradeneeded = function (event) {
  70648. _this.db = (event.target).result;
  70649. if (_this.db) {
  70650. try {
  70651. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  70652. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  70653. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  70654. }
  70655. catch (ex) {
  70656. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  70657. handleError();
  70658. }
  70659. }
  70660. };
  70661. }
  70662. // DB has already been created and opened
  70663. else {
  70664. if (successCallback)
  70665. successCallback();
  70666. }
  70667. }
  70668. };
  70669. /**
  70670. * Loads an image from the database
  70671. * @param url defines the url to load from
  70672. * @param image defines the target DOM image
  70673. */
  70674. Database.prototype.loadImageFromDB = function (url, image) {
  70675. var _this = this;
  70676. var completeURL = Database._ReturnFullUrlLocation(url);
  70677. var saveAndLoadImage = function () {
  70678. if (!_this.hasReachedQuota && _this.db !== null) {
  70679. // the texture is not yet in the DB, let's try to save it
  70680. _this._saveImageIntoDBAsync(completeURL, image);
  70681. }
  70682. // If the texture is not in the DB and we've reached the DB quota limit
  70683. // let's load it directly from the web
  70684. else {
  70685. image.src = url;
  70686. }
  70687. };
  70688. if (!this.mustUpdateRessources) {
  70689. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  70690. }
  70691. // First time we're download the images or update requested in the manifest file by a version change
  70692. else {
  70693. saveAndLoadImage();
  70694. }
  70695. };
  70696. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  70697. if (this.isSupported && this.db !== null) {
  70698. var texture;
  70699. var transaction = this.db.transaction(["textures"]);
  70700. transaction.onabort = function (event) {
  70701. image.src = url;
  70702. };
  70703. transaction.oncomplete = function (event) {
  70704. var blobTextureURL;
  70705. if (texture) {
  70706. var URL = window.URL || window.webkitURL;
  70707. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  70708. image.onerror = function () {
  70709. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  70710. image.src = url;
  70711. };
  70712. image.src = blobTextureURL;
  70713. }
  70714. else {
  70715. notInDBCallback();
  70716. }
  70717. };
  70718. var getRequest = transaction.objectStore("textures").get(url);
  70719. getRequest.onsuccess = function (event) {
  70720. texture = (event.target).result;
  70721. };
  70722. getRequest.onerror = function (event) {
  70723. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  70724. image.src = url;
  70725. };
  70726. }
  70727. else {
  70728. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70729. image.src = url;
  70730. }
  70731. };
  70732. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  70733. var _this = this;
  70734. if (this.isSupported) {
  70735. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  70736. var generateBlobUrl = function () {
  70737. var blobTextureURL;
  70738. if (blob) {
  70739. var URL = window.URL || window.webkitURL;
  70740. try {
  70741. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  70742. }
  70743. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  70744. catch (ex) {
  70745. blobTextureURL = URL.createObjectURL(blob);
  70746. }
  70747. }
  70748. if (blobTextureURL) {
  70749. image.src = blobTextureURL;
  70750. }
  70751. };
  70752. if (Database.IsUASupportingBlobStorage) { // Create XHR
  70753. var xhr = new XMLHttpRequest(), blob;
  70754. xhr.open("GET", url, true);
  70755. xhr.responseType = "blob";
  70756. xhr.addEventListener("load", function () {
  70757. if (xhr.status === 200 && _this.db) {
  70758. // Blob as response (XHR2)
  70759. blob = xhr.response;
  70760. var transaction = _this.db.transaction(["textures"], "readwrite");
  70761. // the transaction could abort because of a QuotaExceededError error
  70762. transaction.onabort = function (event) {
  70763. try {
  70764. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70765. var srcElement = (event.srcElement || event.target);
  70766. var error = srcElement.error;
  70767. if (error && error.name === "QuotaExceededError") {
  70768. _this.hasReachedQuota = true;
  70769. }
  70770. }
  70771. catch (ex) { }
  70772. generateBlobUrl();
  70773. };
  70774. transaction.oncomplete = function (event) {
  70775. generateBlobUrl();
  70776. };
  70777. var newTexture = { textureUrl: url, data: blob };
  70778. try {
  70779. // Put the blob into the dabase
  70780. var addRequest = transaction.objectStore("textures").put(newTexture);
  70781. addRequest.onsuccess = function (event) {
  70782. };
  70783. addRequest.onerror = function (event) {
  70784. generateBlobUrl();
  70785. };
  70786. }
  70787. catch (ex) {
  70788. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  70789. if (ex.code === 25) {
  70790. Database.IsUASupportingBlobStorage = false;
  70791. }
  70792. image.src = url;
  70793. }
  70794. }
  70795. else {
  70796. image.src = url;
  70797. }
  70798. }, false);
  70799. xhr.addEventListener("error", function (event) {
  70800. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  70801. image.src = url;
  70802. }, false);
  70803. xhr.send();
  70804. }
  70805. else {
  70806. image.src = url;
  70807. }
  70808. }
  70809. else {
  70810. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70811. image.src = url;
  70812. }
  70813. };
  70814. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  70815. var _this = this;
  70816. var updateVersion = function () {
  70817. // the version is not yet in the DB or we need to update it
  70818. _this._saveVersionIntoDBAsync(url, versionLoaded);
  70819. };
  70820. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  70821. };
  70822. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  70823. var _this = this;
  70824. if (this.isSupported && this.db) {
  70825. var version;
  70826. try {
  70827. var transaction = this.db.transaction(["versions"]);
  70828. transaction.oncomplete = function (event) {
  70829. if (version) {
  70830. // If the version in the JSON file is different from the version in DB
  70831. if (_this.manifestVersionFound !== version.data) {
  70832. _this.mustUpdateRessources = true;
  70833. updateInDBCallback();
  70834. }
  70835. else {
  70836. callback(version.data);
  70837. }
  70838. }
  70839. // version was not found in DB
  70840. else {
  70841. _this.mustUpdateRessources = true;
  70842. updateInDBCallback();
  70843. }
  70844. };
  70845. transaction.onabort = function (event) {
  70846. callback(-1);
  70847. };
  70848. var getRequest = transaction.objectStore("versions").get(url);
  70849. getRequest.onsuccess = function (event) {
  70850. version = (event.target).result;
  70851. };
  70852. getRequest.onerror = function (event) {
  70853. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  70854. callback(-1);
  70855. };
  70856. }
  70857. catch (ex) {
  70858. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  70859. callback(-1);
  70860. }
  70861. }
  70862. else {
  70863. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70864. callback(-1);
  70865. }
  70866. };
  70867. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  70868. var _this = this;
  70869. if (this.isSupported && !this.hasReachedQuota && this.db) {
  70870. try {
  70871. // Open a transaction to the database
  70872. var transaction = this.db.transaction(["versions"], "readwrite");
  70873. // the transaction could abort because of a QuotaExceededError error
  70874. transaction.onabort = function (event) {
  70875. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70876. var error = event.srcElement['error'];
  70877. if (error && error.name === "QuotaExceededError") {
  70878. _this.hasReachedQuota = true;
  70879. }
  70880. }
  70881. catch (ex) { }
  70882. callback(-1);
  70883. };
  70884. transaction.oncomplete = function (event) {
  70885. callback(_this.manifestVersionFound);
  70886. };
  70887. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  70888. // Put the scene into the database
  70889. var addRequest = transaction.objectStore("versions").put(newVersion);
  70890. addRequest.onsuccess = function (event) {
  70891. };
  70892. addRequest.onerror = function (event) {
  70893. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  70894. };
  70895. }
  70896. catch (ex) {
  70897. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  70898. callback(-1);
  70899. }
  70900. }
  70901. else {
  70902. callback(-1);
  70903. }
  70904. };
  70905. /**
  70906. * Loads a file from database
  70907. * @param url defines the URL to load from
  70908. * @param sceneLoaded defines a callback to call on success
  70909. * @param progressCallBack defines a callback to call when progress changed
  70910. * @param errorCallback defines a callback to call on error
  70911. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  70912. */
  70913. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  70914. var _this = this;
  70915. var completeUrl = Database._ReturnFullUrlLocation(url);
  70916. var saveAndLoadFile = function () {
  70917. // the scene is not yet in the DB, let's try to save it
  70918. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70919. };
  70920. this._checkVersionFromDB(completeUrl, function (version) {
  70921. if (version !== -1) {
  70922. if (!_this.mustUpdateRessources) {
  70923. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  70924. }
  70925. else {
  70926. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70927. }
  70928. }
  70929. else {
  70930. if (errorCallback) {
  70931. errorCallback();
  70932. }
  70933. }
  70934. });
  70935. };
  70936. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  70937. if (this.isSupported && this.db) {
  70938. var targetStore;
  70939. if (url.indexOf(".babylon") !== -1) {
  70940. targetStore = "scenes";
  70941. }
  70942. else {
  70943. targetStore = "textures";
  70944. }
  70945. var file;
  70946. var transaction = this.db.transaction([targetStore]);
  70947. transaction.oncomplete = function (event) {
  70948. if (file) {
  70949. callback(file.data);
  70950. }
  70951. // file was not found in DB
  70952. else {
  70953. notInDBCallback();
  70954. }
  70955. };
  70956. transaction.onabort = function (event) {
  70957. notInDBCallback();
  70958. };
  70959. var getRequest = transaction.objectStore(targetStore).get(url);
  70960. getRequest.onsuccess = function (event) {
  70961. file = (event.target).result;
  70962. };
  70963. getRequest.onerror = function (event) {
  70964. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  70965. notInDBCallback();
  70966. };
  70967. }
  70968. else {
  70969. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70970. callback();
  70971. }
  70972. };
  70973. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  70974. var _this = this;
  70975. if (this.isSupported) {
  70976. var targetStore;
  70977. if (url.indexOf(".babylon") !== -1) {
  70978. targetStore = "scenes";
  70979. }
  70980. else {
  70981. targetStore = "textures";
  70982. }
  70983. // Create XHR
  70984. var xhr = new XMLHttpRequest();
  70985. var fileData;
  70986. xhr.open("GET", url, true);
  70987. if (useArrayBuffer) {
  70988. xhr.responseType = "arraybuffer";
  70989. }
  70990. if (progressCallback) {
  70991. xhr.onprogress = progressCallback;
  70992. }
  70993. xhr.addEventListener("load", function () {
  70994. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  70995. // Blob as response (XHR2)
  70996. //fileData = xhr.responseText;
  70997. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  70998. if (!_this.hasReachedQuota && _this.db) {
  70999. // Open a transaction to the database
  71000. var transaction = _this.db.transaction([targetStore], "readwrite");
  71001. // the transaction could abort because of a QuotaExceededError error
  71002. transaction.onabort = function (event) {
  71003. try {
  71004. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71005. var error = event.srcElement['error'];
  71006. if (error && error.name === "QuotaExceededError") {
  71007. _this.hasReachedQuota = true;
  71008. }
  71009. }
  71010. catch (ex) { }
  71011. callback(fileData);
  71012. };
  71013. transaction.oncomplete = function (event) {
  71014. callback(fileData);
  71015. };
  71016. var newFile;
  71017. if (targetStore === "scenes") {
  71018. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  71019. }
  71020. else {
  71021. newFile = { textureUrl: url, data: fileData };
  71022. }
  71023. try {
  71024. // Put the scene into the database
  71025. var addRequest = transaction.objectStore(targetStore).put(newFile);
  71026. addRequest.onsuccess = function (event) {
  71027. };
  71028. addRequest.onerror = function (event) {
  71029. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  71030. };
  71031. }
  71032. catch (ex) {
  71033. callback(fileData);
  71034. }
  71035. }
  71036. else {
  71037. callback(fileData);
  71038. }
  71039. }
  71040. else {
  71041. if (xhr.status >= 400 && errorCallback) {
  71042. errorCallback(xhr);
  71043. }
  71044. else {
  71045. callback();
  71046. }
  71047. }
  71048. }, false);
  71049. xhr.addEventListener("error", function (event) {
  71050. BABYLON.Tools.Error("error on XHR request.");
  71051. callback();
  71052. }, false);
  71053. xhr.send();
  71054. }
  71055. else {
  71056. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71057. callback();
  71058. }
  71059. };
  71060. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  71061. Database.IsUASupportingBlobStorage = true;
  71062. /** Gets a boolean indicating if Database storate is enabled */
  71063. Database.IDBStorageEnabled = true;
  71064. Database._ParseURL = function (url) {
  71065. var a = document.createElement('a');
  71066. a.href = url;
  71067. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  71068. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  71069. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  71070. return absLocation;
  71071. };
  71072. Database._ReturnFullUrlLocation = function (url) {
  71073. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  71074. return (Database._ParseURL(window.location.href) + url);
  71075. }
  71076. else {
  71077. return url;
  71078. }
  71079. };
  71080. return Database;
  71081. }());
  71082. BABYLON.Database = Database;
  71083. })(BABYLON || (BABYLON = {}));
  71084. //# sourceMappingURL=babylon.database.js.map
  71085. var BABYLON;
  71086. (function (BABYLON) {
  71087. var FresnelParameters = /** @class */ (function () {
  71088. function FresnelParameters() {
  71089. this._isEnabled = true;
  71090. this.leftColor = BABYLON.Color3.White();
  71091. this.rightColor = BABYLON.Color3.Black();
  71092. this.bias = 0;
  71093. this.power = 1;
  71094. }
  71095. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  71096. get: function () {
  71097. return this._isEnabled;
  71098. },
  71099. set: function (value) {
  71100. if (this._isEnabled === value) {
  71101. return;
  71102. }
  71103. this._isEnabled = value;
  71104. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  71105. },
  71106. enumerable: true,
  71107. configurable: true
  71108. });
  71109. FresnelParameters.prototype.clone = function () {
  71110. var newFresnelParameters = new FresnelParameters();
  71111. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  71112. return newFresnelParameters;
  71113. };
  71114. FresnelParameters.prototype.serialize = function () {
  71115. var serializationObject = {};
  71116. serializationObject.isEnabled = this.isEnabled;
  71117. serializationObject.leftColor = this.leftColor.asArray();
  71118. serializationObject.rightColor = this.rightColor.asArray();
  71119. serializationObject.bias = this.bias;
  71120. serializationObject.power = this.power;
  71121. return serializationObject;
  71122. };
  71123. FresnelParameters.Parse = function (parsedFresnelParameters) {
  71124. var fresnelParameters = new FresnelParameters();
  71125. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  71126. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  71127. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  71128. fresnelParameters.bias = parsedFresnelParameters.bias;
  71129. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  71130. return fresnelParameters;
  71131. };
  71132. return FresnelParameters;
  71133. }());
  71134. BABYLON.FresnelParameters = FresnelParameters;
  71135. })(BABYLON || (BABYLON = {}));
  71136. //# sourceMappingURL=babylon.fresnelParameters.js.map
  71137. var BABYLON;
  71138. (function (BABYLON) {
  71139. var MultiMaterial = /** @class */ (function (_super) {
  71140. __extends(MultiMaterial, _super);
  71141. function MultiMaterial(name, scene) {
  71142. var _this = _super.call(this, name, scene, true) || this;
  71143. scene.multiMaterials.push(_this);
  71144. _this.subMaterials = new Array();
  71145. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  71146. return _this;
  71147. }
  71148. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  71149. get: function () {
  71150. return this._subMaterials;
  71151. },
  71152. set: function (value) {
  71153. this._subMaterials = value;
  71154. this._hookArray(value);
  71155. },
  71156. enumerable: true,
  71157. configurable: true
  71158. });
  71159. MultiMaterial.prototype._hookArray = function (array) {
  71160. var _this = this;
  71161. var oldPush = array.push;
  71162. array.push = function () {
  71163. var items = [];
  71164. for (var _i = 0; _i < arguments.length; _i++) {
  71165. items[_i] = arguments[_i];
  71166. }
  71167. var result = oldPush.apply(array, items);
  71168. _this._markAllSubMeshesAsTexturesDirty();
  71169. return result;
  71170. };
  71171. var oldSplice = array.splice;
  71172. array.splice = function (index, deleteCount) {
  71173. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71174. _this._markAllSubMeshesAsTexturesDirty();
  71175. return deleted;
  71176. };
  71177. };
  71178. // Properties
  71179. MultiMaterial.prototype.getSubMaterial = function (index) {
  71180. if (index < 0 || index >= this.subMaterials.length) {
  71181. return this.getScene().defaultMaterial;
  71182. }
  71183. return this.subMaterials[index];
  71184. };
  71185. MultiMaterial.prototype.getActiveTextures = function () {
  71186. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  71187. if (subMaterial) {
  71188. return subMaterial.getActiveTextures();
  71189. }
  71190. else {
  71191. return [];
  71192. }
  71193. }));
  71194. var _a;
  71195. };
  71196. // Methods
  71197. MultiMaterial.prototype.getClassName = function () {
  71198. return "MultiMaterial";
  71199. };
  71200. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71201. for (var index = 0; index < this.subMaterials.length; index++) {
  71202. var subMaterial = this.subMaterials[index];
  71203. if (subMaterial) {
  71204. if (subMaterial.storeEffectOnSubMeshes) {
  71205. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  71206. return false;
  71207. }
  71208. continue;
  71209. }
  71210. if (!subMaterial.isReady(mesh)) {
  71211. return false;
  71212. }
  71213. }
  71214. }
  71215. return true;
  71216. };
  71217. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  71218. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  71219. for (var index = 0; index < this.subMaterials.length; index++) {
  71220. var subMaterial = null;
  71221. var current = this.subMaterials[index];
  71222. if (cloneChildren && current) {
  71223. subMaterial = current.clone(name + "-" + current.name);
  71224. }
  71225. else {
  71226. subMaterial = this.subMaterials[index];
  71227. }
  71228. newMultiMaterial.subMaterials.push(subMaterial);
  71229. }
  71230. return newMultiMaterial;
  71231. };
  71232. MultiMaterial.prototype.serialize = function () {
  71233. var serializationObject = {};
  71234. serializationObject.name = this.name;
  71235. serializationObject.id = this.id;
  71236. if (BABYLON.Tags) {
  71237. serializationObject.tags = BABYLON.Tags.GetTags(this);
  71238. }
  71239. serializationObject.materials = [];
  71240. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  71241. var subMat = this.subMaterials[matIndex];
  71242. if (subMat) {
  71243. serializationObject.materials.push(subMat.id);
  71244. }
  71245. else {
  71246. serializationObject.materials.push(null);
  71247. }
  71248. }
  71249. return serializationObject;
  71250. };
  71251. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  71252. var scene = this.getScene();
  71253. if (!scene) {
  71254. return;
  71255. }
  71256. var index = scene.multiMaterials.indexOf(this);
  71257. if (index >= 0) {
  71258. scene.multiMaterials.splice(index, 1);
  71259. }
  71260. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  71261. };
  71262. return MultiMaterial;
  71263. }(BABYLON.Material));
  71264. BABYLON.MultiMaterial = MultiMaterial;
  71265. })(BABYLON || (BABYLON = {}));
  71266. //# sourceMappingURL=babylon.multiMaterial.js.map
  71267. var BABYLON;
  71268. (function (BABYLON) {
  71269. var FreeCameraTouchInput = /** @class */ (function () {
  71270. function FreeCameraTouchInput() {
  71271. this._offsetX = null;
  71272. this._offsetY = null;
  71273. this._pointerPressed = new Array();
  71274. this.touchAngularSensibility = 200000.0;
  71275. this.touchMoveSensibility = 250.0;
  71276. }
  71277. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  71278. var _this = this;
  71279. var previousPosition = null;
  71280. if (this._pointerInput === undefined) {
  71281. this._onLostFocus = function (evt) {
  71282. _this._offsetX = null;
  71283. _this._offsetY = null;
  71284. };
  71285. this._pointerInput = function (p, s) {
  71286. var evt = p.event;
  71287. if (evt.pointerType === "mouse") {
  71288. return;
  71289. }
  71290. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71291. if (!noPreventDefault) {
  71292. evt.preventDefault();
  71293. }
  71294. _this._pointerPressed.push(evt.pointerId);
  71295. if (_this._pointerPressed.length !== 1) {
  71296. return;
  71297. }
  71298. previousPosition = {
  71299. x: evt.clientX,
  71300. y: evt.clientY
  71301. };
  71302. }
  71303. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  71304. if (!noPreventDefault) {
  71305. evt.preventDefault();
  71306. }
  71307. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71308. if (index === -1) {
  71309. return;
  71310. }
  71311. _this._pointerPressed.splice(index, 1);
  71312. if (index != 0) {
  71313. return;
  71314. }
  71315. previousPosition = null;
  71316. _this._offsetX = null;
  71317. _this._offsetY = null;
  71318. }
  71319. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  71320. if (!noPreventDefault) {
  71321. evt.preventDefault();
  71322. }
  71323. if (!previousPosition) {
  71324. return;
  71325. }
  71326. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71327. if (index != 0) {
  71328. return;
  71329. }
  71330. _this._offsetX = evt.clientX - previousPosition.x;
  71331. _this._offsetY = -(evt.clientY - previousPosition.y);
  71332. }
  71333. };
  71334. }
  71335. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  71336. if (this._onLostFocus) {
  71337. element.addEventListener("blur", this._onLostFocus);
  71338. }
  71339. };
  71340. FreeCameraTouchInput.prototype.detachControl = function (element) {
  71341. if (this._pointerInput && element) {
  71342. if (this._observer) {
  71343. this.camera.getScene().onPointerObservable.remove(this._observer);
  71344. this._observer = null;
  71345. }
  71346. if (this._onLostFocus) {
  71347. element.removeEventListener("blur", this._onLostFocus);
  71348. this._onLostFocus = null;
  71349. }
  71350. this._pointerPressed = [];
  71351. this._offsetX = null;
  71352. this._offsetY = null;
  71353. }
  71354. };
  71355. FreeCameraTouchInput.prototype.checkInputs = function () {
  71356. if (this._offsetX && this._offsetY) {
  71357. var camera = this.camera;
  71358. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  71359. if (this._pointerPressed.length > 1) {
  71360. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  71361. }
  71362. else {
  71363. var speed = camera._computeLocalCameraSpeed();
  71364. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  71365. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  71366. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  71367. }
  71368. }
  71369. };
  71370. FreeCameraTouchInput.prototype.getClassName = function () {
  71371. return "FreeCameraTouchInput";
  71372. };
  71373. FreeCameraTouchInput.prototype.getSimpleName = function () {
  71374. return "touch";
  71375. };
  71376. __decorate([
  71377. BABYLON.serialize()
  71378. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  71379. __decorate([
  71380. BABYLON.serialize()
  71381. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  71382. return FreeCameraTouchInput;
  71383. }());
  71384. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  71385. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  71386. })(BABYLON || (BABYLON = {}));
  71387. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  71388. var BABYLON;
  71389. (function (BABYLON) {
  71390. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  71391. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  71392. });
  71393. // We're mainly based on the logic defined into the FreeCamera code
  71394. var TouchCamera = /** @class */ (function (_super) {
  71395. __extends(TouchCamera, _super);
  71396. //-- end properties for backward compatibility for inputs
  71397. function TouchCamera(name, position, scene) {
  71398. var _this = _super.call(this, name, position, scene) || this;
  71399. _this.inputs.addTouch();
  71400. _this._setupInputs();
  71401. return _this;
  71402. }
  71403. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  71404. //-- Begin properties for backward compatibility for inputs
  71405. get: function () {
  71406. var touch = this.inputs.attached["touch"];
  71407. if (touch)
  71408. return touch.touchAngularSensibility;
  71409. return 0;
  71410. },
  71411. set: function (value) {
  71412. var touch = this.inputs.attached["touch"];
  71413. if (touch)
  71414. touch.touchAngularSensibility = value;
  71415. },
  71416. enumerable: true,
  71417. configurable: true
  71418. });
  71419. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  71420. get: function () {
  71421. var touch = this.inputs.attached["touch"];
  71422. if (touch)
  71423. return touch.touchMoveSensibility;
  71424. return 0;
  71425. },
  71426. set: function (value) {
  71427. var touch = this.inputs.attached["touch"];
  71428. if (touch)
  71429. touch.touchMoveSensibility = value;
  71430. },
  71431. enumerable: true,
  71432. configurable: true
  71433. });
  71434. TouchCamera.prototype.getClassName = function () {
  71435. return "TouchCamera";
  71436. };
  71437. TouchCamera.prototype._setupInputs = function () {
  71438. var mouse = this.inputs.attached["mouse"];
  71439. if (mouse) {
  71440. mouse.touchEnabled = false;
  71441. }
  71442. };
  71443. return TouchCamera;
  71444. }(BABYLON.FreeCamera));
  71445. BABYLON.TouchCamera = TouchCamera;
  71446. })(BABYLON || (BABYLON = {}));
  71447. //# sourceMappingURL=babylon.touchCamera.js.map
  71448. var BABYLON;
  71449. (function (BABYLON) {
  71450. var ProceduralTexture = /** @class */ (function (_super) {
  71451. __extends(ProceduralTexture, _super);
  71452. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  71453. if (fallbackTexture === void 0) { fallbackTexture = null; }
  71454. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71455. if (isCube === void 0) { isCube = false; }
  71456. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71457. _this.isCube = isCube;
  71458. _this.isEnabled = true;
  71459. _this._currentRefreshId = -1;
  71460. _this._refreshRate = 1;
  71461. _this._vertexBuffers = {};
  71462. _this._uniforms = new Array();
  71463. _this._samplers = new Array();
  71464. _this._textures = {};
  71465. _this._floats = {};
  71466. _this._ints = {};
  71467. _this._floatsArrays = {};
  71468. _this._colors3 = {};
  71469. _this._colors4 = {};
  71470. _this._vectors2 = {};
  71471. _this._vectors3 = {};
  71472. _this._matrices = {};
  71473. _this._fallbackTextureUsed = false;
  71474. scene = _this.getScene();
  71475. scene.proceduralTextures.push(_this);
  71476. _this._engine = scene.getEngine();
  71477. _this.name = name;
  71478. _this.isRenderTarget = true;
  71479. _this._size = size;
  71480. _this._generateMipMaps = generateMipMaps;
  71481. _this.setFragment(fragment);
  71482. _this._fallbackTexture = fallbackTexture;
  71483. if (isCube) {
  71484. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  71485. _this.setFloat("face", 0);
  71486. }
  71487. else {
  71488. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  71489. }
  71490. // VBO
  71491. var vertices = [];
  71492. vertices.push(1, 1);
  71493. vertices.push(-1, 1);
  71494. vertices.push(-1, -1);
  71495. vertices.push(1, -1);
  71496. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71497. _this._createIndexBuffer();
  71498. return _this;
  71499. }
  71500. ProceduralTexture.prototype._createIndexBuffer = function () {
  71501. var engine = this._engine;
  71502. // Indices
  71503. var indices = [];
  71504. indices.push(0);
  71505. indices.push(1);
  71506. indices.push(2);
  71507. indices.push(0);
  71508. indices.push(2);
  71509. indices.push(3);
  71510. this._indexBuffer = engine.createIndexBuffer(indices);
  71511. };
  71512. ProceduralTexture.prototype._rebuild = function () {
  71513. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71514. if (vb) {
  71515. vb._rebuild();
  71516. }
  71517. this._createIndexBuffer();
  71518. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71519. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71520. }
  71521. };
  71522. ProceduralTexture.prototype.reset = function () {
  71523. if (this._effect === undefined) {
  71524. return;
  71525. }
  71526. var engine = this._engine;
  71527. engine._releaseEffect(this._effect);
  71528. };
  71529. ProceduralTexture.prototype.isReady = function () {
  71530. var _this = this;
  71531. var engine = this._engine;
  71532. var shaders;
  71533. if (!this._fragment) {
  71534. return false;
  71535. }
  71536. if (this._fallbackTextureUsed) {
  71537. return true;
  71538. }
  71539. if (this._fragment.fragmentElement !== undefined) {
  71540. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  71541. }
  71542. else {
  71543. shaders = { vertex: "procedural", fragment: this._fragment };
  71544. }
  71545. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  71546. _this.releaseInternalTexture();
  71547. if (_this._fallbackTexture) {
  71548. _this._texture = _this._fallbackTexture._texture;
  71549. if (_this._texture) {
  71550. _this._texture.incrementReferences();
  71551. }
  71552. }
  71553. _this._fallbackTextureUsed = true;
  71554. });
  71555. return this._effect.isReady();
  71556. };
  71557. ProceduralTexture.prototype.resetRefreshCounter = function () {
  71558. this._currentRefreshId = -1;
  71559. };
  71560. ProceduralTexture.prototype.setFragment = function (fragment) {
  71561. this._fragment = fragment;
  71562. };
  71563. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  71564. get: function () {
  71565. return this._refreshRate;
  71566. },
  71567. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71568. set: function (value) {
  71569. this._refreshRate = value;
  71570. this.resetRefreshCounter();
  71571. },
  71572. enumerable: true,
  71573. configurable: true
  71574. });
  71575. ProceduralTexture.prototype._shouldRender = function () {
  71576. if (!this.isEnabled || !this.isReady() || !this._texture) {
  71577. return false;
  71578. }
  71579. if (this._fallbackTextureUsed) {
  71580. return false;
  71581. }
  71582. if (this._currentRefreshId === -1) { // At least render once
  71583. this._currentRefreshId = 1;
  71584. return true;
  71585. }
  71586. if (this.refreshRate === this._currentRefreshId) {
  71587. this._currentRefreshId = 1;
  71588. return true;
  71589. }
  71590. this._currentRefreshId++;
  71591. return false;
  71592. };
  71593. ProceduralTexture.prototype.getRenderSize = function () {
  71594. return this._size;
  71595. };
  71596. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  71597. if (this._fallbackTextureUsed) {
  71598. return;
  71599. }
  71600. this.releaseInternalTexture();
  71601. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  71602. // Update properties
  71603. this._size = size;
  71604. this._generateMipMaps = generateMipMaps;
  71605. };
  71606. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  71607. if (this._uniforms.indexOf(uniformName) === -1) {
  71608. this._uniforms.push(uniformName);
  71609. }
  71610. };
  71611. ProceduralTexture.prototype.setTexture = function (name, texture) {
  71612. if (this._samplers.indexOf(name) === -1) {
  71613. this._samplers.push(name);
  71614. }
  71615. this._textures[name] = texture;
  71616. return this;
  71617. };
  71618. ProceduralTexture.prototype.setFloat = function (name, value) {
  71619. this._checkUniform(name);
  71620. this._floats[name] = value;
  71621. return this;
  71622. };
  71623. /**
  71624. * Set the value of an uniform to an integer value
  71625. * @param name defines the name of the uniform
  71626. * @param value defines the value to set
  71627. * @returns the current procedural texture
  71628. */
  71629. ProceduralTexture.prototype.setInt = function (name, value) {
  71630. this._checkUniform(name);
  71631. this._ints[name] = value;
  71632. return this;
  71633. };
  71634. ProceduralTexture.prototype.setFloats = function (name, value) {
  71635. this._checkUniform(name);
  71636. this._floatsArrays[name] = value;
  71637. return this;
  71638. };
  71639. ProceduralTexture.prototype.setColor3 = function (name, value) {
  71640. this._checkUniform(name);
  71641. this._colors3[name] = value;
  71642. return this;
  71643. };
  71644. ProceduralTexture.prototype.setColor4 = function (name, value) {
  71645. this._checkUniform(name);
  71646. this._colors4[name] = value;
  71647. return this;
  71648. };
  71649. ProceduralTexture.prototype.setVector2 = function (name, value) {
  71650. this._checkUniform(name);
  71651. this._vectors2[name] = value;
  71652. return this;
  71653. };
  71654. ProceduralTexture.prototype.setVector3 = function (name, value) {
  71655. this._checkUniform(name);
  71656. this._vectors3[name] = value;
  71657. return this;
  71658. };
  71659. ProceduralTexture.prototype.setMatrix = function (name, value) {
  71660. this._checkUniform(name);
  71661. this._matrices[name] = value;
  71662. return this;
  71663. };
  71664. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71665. var scene = this.getScene();
  71666. if (!scene) {
  71667. return;
  71668. }
  71669. var engine = this._engine;
  71670. // Render
  71671. engine.enableEffect(this._effect);
  71672. engine.setState(false);
  71673. // Texture
  71674. for (var name in this._textures) {
  71675. this._effect.setTexture(name, this._textures[name]);
  71676. }
  71677. // Float
  71678. for (name in this._ints) {
  71679. this._effect.setInt(name, this._ints[name]);
  71680. }
  71681. // Float
  71682. for (name in this._floats) {
  71683. this._effect.setFloat(name, this._floats[name]);
  71684. }
  71685. // Floats
  71686. for (name in this._floatsArrays) {
  71687. this._effect.setArray(name, this._floatsArrays[name]);
  71688. }
  71689. // Color3
  71690. for (name in this._colors3) {
  71691. this._effect.setColor3(name, this._colors3[name]);
  71692. }
  71693. // Color4
  71694. for (name in this._colors4) {
  71695. var color = this._colors4[name];
  71696. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  71697. }
  71698. // Vector2
  71699. for (name in this._vectors2) {
  71700. this._effect.setVector2(name, this._vectors2[name]);
  71701. }
  71702. // Vector3
  71703. for (name in this._vectors3) {
  71704. this._effect.setVector3(name, this._vectors3[name]);
  71705. }
  71706. // Matrix
  71707. for (name in this._matrices) {
  71708. this._effect.setMatrix(name, this._matrices[name]);
  71709. }
  71710. if (!this._texture) {
  71711. return;
  71712. }
  71713. if (this.isCube) {
  71714. for (var face = 0; face < 6; face++) {
  71715. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  71716. // VBOs
  71717. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71718. this._effect.setFloat("face", face);
  71719. // Clear
  71720. engine.clear(scene.clearColor, true, true, true);
  71721. // Draw order
  71722. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71723. // Mipmaps
  71724. if (face === 5) {
  71725. engine.generateMipMapsForCubemap(this._texture);
  71726. }
  71727. }
  71728. }
  71729. else {
  71730. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  71731. // VBOs
  71732. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71733. // Clear
  71734. engine.clear(scene.clearColor, true, true, true);
  71735. // Draw order
  71736. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71737. }
  71738. // Unbind
  71739. engine.unBindFramebuffer(this._texture, this.isCube);
  71740. if (this.onGenerated) {
  71741. this.onGenerated();
  71742. }
  71743. };
  71744. ProceduralTexture.prototype.clone = function () {
  71745. var textureSize = this.getSize();
  71746. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  71747. // Base texture
  71748. newTexture.hasAlpha = this.hasAlpha;
  71749. newTexture.level = this.level;
  71750. // RenderTarget Texture
  71751. newTexture.coordinatesMode = this.coordinatesMode;
  71752. return newTexture;
  71753. };
  71754. ProceduralTexture.prototype.dispose = function () {
  71755. var scene = this.getScene();
  71756. if (!scene) {
  71757. return;
  71758. }
  71759. var index = scene.proceduralTextures.indexOf(this);
  71760. if (index >= 0) {
  71761. scene.proceduralTextures.splice(index, 1);
  71762. }
  71763. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71764. if (vertexBuffer) {
  71765. vertexBuffer.dispose();
  71766. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71767. }
  71768. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  71769. this._indexBuffer = null;
  71770. }
  71771. _super.prototype.dispose.call(this);
  71772. };
  71773. __decorate([
  71774. BABYLON.serialize()
  71775. ], ProceduralTexture.prototype, "_size", void 0);
  71776. __decorate([
  71777. BABYLON.serialize()
  71778. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  71779. __decorate([
  71780. BABYLON.serialize()
  71781. ], ProceduralTexture.prototype, "isEnabled", void 0);
  71782. __decorate([
  71783. BABYLON.serialize()
  71784. ], ProceduralTexture.prototype, "refreshRate", null);
  71785. return ProceduralTexture;
  71786. }(BABYLON.Texture));
  71787. BABYLON.ProceduralTexture = ProceduralTexture;
  71788. })(BABYLON || (BABYLON = {}));
  71789. //# sourceMappingURL=babylon.proceduralTexture.js.map
  71790. var BABYLON;
  71791. (function (BABYLON) {
  71792. var CustomProceduralTexture = /** @class */ (function (_super) {
  71793. __extends(CustomProceduralTexture, _super);
  71794. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  71795. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  71796. _this._animate = true;
  71797. _this._time = 0;
  71798. _this._texturePath = texturePath;
  71799. //Try to load json
  71800. _this.loadJson(texturePath);
  71801. _this.refreshRate = 1;
  71802. return _this;
  71803. }
  71804. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  71805. var _this = this;
  71806. var noConfigFile = function () {
  71807. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  71808. try {
  71809. _this.setFragment(_this._texturePath);
  71810. }
  71811. catch (ex) {
  71812. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  71813. }
  71814. };
  71815. var configFileUrl = jsonUrl + "/config.json";
  71816. var xhr = new XMLHttpRequest();
  71817. xhr.open("GET", configFileUrl, true);
  71818. xhr.addEventListener("load", function () {
  71819. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71820. try {
  71821. _this._config = JSON.parse(xhr.response);
  71822. _this.updateShaderUniforms();
  71823. _this.updateTextures();
  71824. _this.setFragment(_this._texturePath + "/custom");
  71825. _this._animate = _this._config.animate;
  71826. _this.refreshRate = _this._config.refreshrate;
  71827. }
  71828. catch (ex) {
  71829. noConfigFile();
  71830. }
  71831. }
  71832. else {
  71833. noConfigFile();
  71834. }
  71835. }, false);
  71836. xhr.addEventListener("error", function () {
  71837. noConfigFile();
  71838. }, false);
  71839. try {
  71840. xhr.send();
  71841. }
  71842. catch (ex) {
  71843. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  71844. }
  71845. };
  71846. CustomProceduralTexture.prototype.isReady = function () {
  71847. if (!_super.prototype.isReady.call(this)) {
  71848. return false;
  71849. }
  71850. for (var name in this._textures) {
  71851. var texture = this._textures[name];
  71852. if (!texture.isReady()) {
  71853. return false;
  71854. }
  71855. }
  71856. return true;
  71857. };
  71858. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71859. var scene = this.getScene();
  71860. if (this._animate && scene) {
  71861. this._time += scene.getAnimationRatio() * 0.03;
  71862. this.updateShaderUniforms();
  71863. }
  71864. _super.prototype.render.call(this, useCameraPostProcess);
  71865. };
  71866. CustomProceduralTexture.prototype.updateTextures = function () {
  71867. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  71868. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  71869. }
  71870. };
  71871. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  71872. if (this._config) {
  71873. for (var j = 0; j < this._config.uniforms.length; j++) {
  71874. var uniform = this._config.uniforms[j];
  71875. switch (uniform.type) {
  71876. case "float":
  71877. this.setFloat(uniform.name, uniform.value);
  71878. break;
  71879. case "color3":
  71880. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  71881. break;
  71882. case "color4":
  71883. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  71884. break;
  71885. case "vector2":
  71886. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  71887. break;
  71888. case "vector3":
  71889. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  71890. break;
  71891. }
  71892. }
  71893. }
  71894. this.setFloat("time", this._time);
  71895. };
  71896. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  71897. get: function () {
  71898. return this._animate;
  71899. },
  71900. set: function (value) {
  71901. this._animate = value;
  71902. },
  71903. enumerable: true,
  71904. configurable: true
  71905. });
  71906. return CustomProceduralTexture;
  71907. }(BABYLON.ProceduralTexture));
  71908. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  71909. })(BABYLON || (BABYLON = {}));
  71910. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  71911. var BABYLON;
  71912. (function (BABYLON) {
  71913. var FreeCameraGamepadInput = /** @class */ (function () {
  71914. function FreeCameraGamepadInput() {
  71915. this.gamepadAngularSensibility = 200;
  71916. this.gamepadMoveSensibility = 40;
  71917. // private members
  71918. this._cameraTransform = BABYLON.Matrix.Identity();
  71919. this._deltaTransform = BABYLON.Vector3.Zero();
  71920. this._vector3 = BABYLON.Vector3.Zero();
  71921. this._vector2 = BABYLON.Vector2.Zero();
  71922. }
  71923. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71924. var _this = this;
  71925. var manager = this.camera.getScene().gamepadManager;
  71926. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71927. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71928. // prioritize XBOX gamepads.
  71929. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71930. _this.gamepad = gamepad;
  71931. }
  71932. }
  71933. });
  71934. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71935. if (_this.gamepad === gamepad) {
  71936. _this.gamepad = null;
  71937. }
  71938. });
  71939. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71940. };
  71941. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  71942. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71943. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71944. this.gamepad = null;
  71945. };
  71946. FreeCameraGamepadInput.prototype.checkInputs = function () {
  71947. if (this.gamepad && this.gamepad.leftStick) {
  71948. var camera = this.camera;
  71949. var LSValues = this.gamepad.leftStick;
  71950. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  71951. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71952. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  71953. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  71954. var RSValues = this.gamepad.rightStick;
  71955. if (RSValues) {
  71956. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  71957. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  71958. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  71959. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  71960. }
  71961. else {
  71962. RSValues = { x: 0, y: 0 };
  71963. }
  71964. if (!camera.rotationQuaternion) {
  71965. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  71966. }
  71967. else {
  71968. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  71969. }
  71970. var speed = camera._computeLocalCameraSpeed() * 50.0;
  71971. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  71972. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  71973. camera.cameraDirection.addInPlace(this._deltaTransform);
  71974. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  71975. camera.cameraRotation.addInPlace(this._vector2);
  71976. }
  71977. };
  71978. FreeCameraGamepadInput.prototype.getClassName = function () {
  71979. return "FreeCameraGamepadInput";
  71980. };
  71981. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  71982. return "gamepad";
  71983. };
  71984. __decorate([
  71985. BABYLON.serialize()
  71986. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  71987. __decorate([
  71988. BABYLON.serialize()
  71989. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71990. return FreeCameraGamepadInput;
  71991. }());
  71992. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  71993. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  71994. })(BABYLON || (BABYLON = {}));
  71995. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  71996. var BABYLON;
  71997. (function (BABYLON) {
  71998. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  71999. function ArcRotateCameraGamepadInput() {
  72000. this.gamepadRotationSensibility = 80;
  72001. this.gamepadMoveSensibility = 40;
  72002. }
  72003. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72004. var _this = this;
  72005. var manager = this.camera.getScene().gamepadManager;
  72006. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72007. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72008. // prioritize XBOX gamepads.
  72009. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72010. _this.gamepad = gamepad;
  72011. }
  72012. }
  72013. });
  72014. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72015. if (_this.gamepad === gamepad) {
  72016. _this.gamepad = null;
  72017. }
  72018. });
  72019. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72020. };
  72021. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  72022. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72023. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72024. this.gamepad = null;
  72025. };
  72026. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  72027. if (this.gamepad) {
  72028. var camera = this.camera;
  72029. var RSValues = this.gamepad.rightStick;
  72030. if (RSValues) {
  72031. if (RSValues.x != 0) {
  72032. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  72033. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  72034. camera.inertialAlphaOffset += normalizedRX;
  72035. }
  72036. }
  72037. if (RSValues.y != 0) {
  72038. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  72039. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  72040. camera.inertialBetaOffset += normalizedRY;
  72041. }
  72042. }
  72043. }
  72044. var LSValues = this.gamepad.leftStick;
  72045. if (LSValues && LSValues.y != 0) {
  72046. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72047. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  72048. this.camera.inertialRadiusOffset -= normalizedLY;
  72049. }
  72050. }
  72051. }
  72052. };
  72053. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  72054. return "ArcRotateCameraGamepadInput";
  72055. };
  72056. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  72057. return "gamepad";
  72058. };
  72059. __decorate([
  72060. BABYLON.serialize()
  72061. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  72062. __decorate([
  72063. BABYLON.serialize()
  72064. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72065. return ArcRotateCameraGamepadInput;
  72066. }());
  72067. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  72068. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  72069. })(BABYLON || (BABYLON = {}));
  72070. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  72071. var BABYLON;
  72072. (function (BABYLON) {
  72073. var GamepadManager = /** @class */ (function () {
  72074. function GamepadManager(_scene) {
  72075. var _this = this;
  72076. this._scene = _scene;
  72077. this._babylonGamepads = [];
  72078. this._oneGamepadConnected = false;
  72079. this._isMonitoring = false;
  72080. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  72081. if (!BABYLON.Tools.IsWindowObjectExist()) {
  72082. this._gamepadEventSupported = false;
  72083. }
  72084. else {
  72085. this._gamepadEventSupported = 'GamepadEvent' in window;
  72086. this._gamepadSupport = (navigator.getGamepads ||
  72087. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  72088. }
  72089. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  72090. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  72091. for (var i in _this._babylonGamepads) {
  72092. var gamepad = _this._babylonGamepads[i];
  72093. if (gamepad && gamepad._isConnected) {
  72094. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  72095. }
  72096. }
  72097. });
  72098. this._onGamepadConnectedEvent = function (evt) {
  72099. var gamepad = evt.gamepad;
  72100. if (gamepad.index in _this._babylonGamepads) {
  72101. if (_this._babylonGamepads[gamepad.index].isConnected) {
  72102. return;
  72103. }
  72104. }
  72105. var newGamepad;
  72106. if (_this._babylonGamepads[gamepad.index]) {
  72107. newGamepad = _this._babylonGamepads[gamepad.index];
  72108. newGamepad.browserGamepad = gamepad;
  72109. newGamepad._isConnected = true;
  72110. }
  72111. else {
  72112. newGamepad = _this._addNewGamepad(gamepad);
  72113. }
  72114. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72115. _this._startMonitoringGamepads();
  72116. };
  72117. this._onGamepadDisconnectedEvent = function (evt) {
  72118. var gamepad = evt.gamepad;
  72119. // Remove the gamepad from the list of gamepads to monitor.
  72120. for (var i in _this._babylonGamepads) {
  72121. if (_this._babylonGamepads[i].index === gamepad.index) {
  72122. var disconnectedGamepad = _this._babylonGamepads[i];
  72123. disconnectedGamepad._isConnected = false;
  72124. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  72125. break;
  72126. }
  72127. }
  72128. };
  72129. if (this._gamepadSupport) {
  72130. //first add already-connected gamepads
  72131. this._updateGamepadObjects();
  72132. if (this._babylonGamepads.length) {
  72133. this._startMonitoringGamepads();
  72134. }
  72135. // Checking if the gamepad connected event is supported (like in Firefox)
  72136. if (this._gamepadEventSupported) {
  72137. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  72138. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  72139. }
  72140. else {
  72141. this._startMonitoringGamepads();
  72142. }
  72143. }
  72144. }
  72145. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  72146. get: function () {
  72147. return this._babylonGamepads;
  72148. },
  72149. enumerable: true,
  72150. configurable: true
  72151. });
  72152. GamepadManager.prototype.getGamepadByType = function (type) {
  72153. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  72154. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  72155. var gamepad = _a[_i];
  72156. if (gamepad && gamepad.type === type) {
  72157. return gamepad;
  72158. }
  72159. }
  72160. return null;
  72161. };
  72162. GamepadManager.prototype.dispose = function () {
  72163. if (this._gamepadEventSupported) {
  72164. if (this._onGamepadConnectedEvent) {
  72165. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  72166. }
  72167. if (this._onGamepadDisconnectedEvent) {
  72168. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  72169. }
  72170. this._onGamepadConnectedEvent = null;
  72171. this._onGamepadDisconnectedEvent = null;
  72172. }
  72173. this._babylonGamepads.forEach(function (gamepad) {
  72174. gamepad.dispose();
  72175. });
  72176. this.onGamepadConnectedObservable.clear();
  72177. this.onGamepadDisconnectedObservable.clear();
  72178. this._oneGamepadConnected = false;
  72179. this._stopMonitoringGamepads();
  72180. this._babylonGamepads = [];
  72181. };
  72182. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  72183. if (!this._oneGamepadConnected) {
  72184. this._oneGamepadConnected = true;
  72185. }
  72186. var newGamepad;
  72187. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  72188. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  72189. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  72190. }
  72191. // if pose is supported, use the (WebVR) pose enabled controller
  72192. else if (gamepad.pose) {
  72193. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  72194. }
  72195. else {
  72196. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  72197. }
  72198. this._babylonGamepads[newGamepad.index] = newGamepad;
  72199. return newGamepad;
  72200. };
  72201. GamepadManager.prototype._startMonitoringGamepads = function () {
  72202. if (!this._isMonitoring) {
  72203. this._isMonitoring = true;
  72204. //back-comp
  72205. if (!this._scene) {
  72206. this._checkGamepadsStatus();
  72207. }
  72208. }
  72209. };
  72210. GamepadManager.prototype._stopMonitoringGamepads = function () {
  72211. this._isMonitoring = false;
  72212. };
  72213. GamepadManager.prototype._checkGamepadsStatus = function () {
  72214. var _this = this;
  72215. // Hack to be compatible Chrome
  72216. this._updateGamepadObjects();
  72217. for (var i in this._babylonGamepads) {
  72218. var gamepad = this._babylonGamepads[i];
  72219. if (!gamepad || !gamepad.isConnected) {
  72220. continue;
  72221. }
  72222. gamepad.update();
  72223. }
  72224. if (this._isMonitoring && !this._scene) {
  72225. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  72226. }
  72227. };
  72228. // This function is called only on Chrome, which does not properly support
  72229. // connection/disconnection events and forces you to recopy again the gamepad object
  72230. GamepadManager.prototype._updateGamepadObjects = function () {
  72231. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  72232. for (var i = 0; i < gamepads.length; i++) {
  72233. var gamepad = gamepads[i];
  72234. if (gamepad) {
  72235. if (!this._babylonGamepads[gamepad.index]) {
  72236. var newGamepad = this._addNewGamepad(gamepad);
  72237. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72238. }
  72239. else {
  72240. // Forced to copy again this object for Chrome for unknown reason
  72241. this._babylonGamepads[i].browserGamepad = gamepad;
  72242. if (!this._babylonGamepads[i].isConnected) {
  72243. this._babylonGamepads[i]._isConnected = true;
  72244. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  72245. }
  72246. }
  72247. }
  72248. }
  72249. };
  72250. return GamepadManager;
  72251. }());
  72252. BABYLON.GamepadManager = GamepadManager;
  72253. })(BABYLON || (BABYLON = {}));
  72254. //# sourceMappingURL=babylon.gamepadManager.js.map
  72255. var BABYLON;
  72256. (function (BABYLON) {
  72257. var StickValues = /** @class */ (function () {
  72258. function StickValues(x, y) {
  72259. this.x = x;
  72260. this.y = y;
  72261. }
  72262. return StickValues;
  72263. }());
  72264. BABYLON.StickValues = StickValues;
  72265. var Gamepad = /** @class */ (function () {
  72266. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  72267. if (leftStickX === void 0) { leftStickX = 0; }
  72268. if (leftStickY === void 0) { leftStickY = 1; }
  72269. if (rightStickX === void 0) { rightStickX = 2; }
  72270. if (rightStickY === void 0) { rightStickY = 3; }
  72271. this.id = id;
  72272. this.index = index;
  72273. this.browserGamepad = browserGamepad;
  72274. this._isConnected = true;
  72275. this._invertLeftStickY = false;
  72276. this.type = Gamepad.GAMEPAD;
  72277. this._leftStickAxisX = leftStickX;
  72278. this._leftStickAxisY = leftStickY;
  72279. this._rightStickAxisX = rightStickX;
  72280. this._rightStickAxisY = rightStickY;
  72281. if (this.browserGamepad.axes.length >= 2) {
  72282. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72283. }
  72284. if (this.browserGamepad.axes.length >= 4) {
  72285. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72286. }
  72287. }
  72288. Object.defineProperty(Gamepad.prototype, "isConnected", {
  72289. get: function () {
  72290. return this._isConnected;
  72291. },
  72292. enumerable: true,
  72293. configurable: true
  72294. });
  72295. Gamepad.prototype.onleftstickchanged = function (callback) {
  72296. this._onleftstickchanged = callback;
  72297. };
  72298. Gamepad.prototype.onrightstickchanged = function (callback) {
  72299. this._onrightstickchanged = callback;
  72300. };
  72301. Object.defineProperty(Gamepad.prototype, "leftStick", {
  72302. get: function () {
  72303. return this._leftStick;
  72304. },
  72305. set: function (newValues) {
  72306. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  72307. this._onleftstickchanged(newValues);
  72308. }
  72309. this._leftStick = newValues;
  72310. },
  72311. enumerable: true,
  72312. configurable: true
  72313. });
  72314. Object.defineProperty(Gamepad.prototype, "rightStick", {
  72315. get: function () {
  72316. return this._rightStick;
  72317. },
  72318. set: function (newValues) {
  72319. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  72320. this._onrightstickchanged(newValues);
  72321. }
  72322. this._rightStick = newValues;
  72323. },
  72324. enumerable: true,
  72325. configurable: true
  72326. });
  72327. Gamepad.prototype.update = function () {
  72328. if (this._leftStick) {
  72329. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72330. if (this._invertLeftStickY) {
  72331. this.leftStick.y *= -1;
  72332. }
  72333. }
  72334. if (this._rightStick) {
  72335. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72336. }
  72337. };
  72338. Gamepad.prototype.dispose = function () {
  72339. };
  72340. Gamepad.GAMEPAD = 0;
  72341. Gamepad.GENERIC = 1;
  72342. Gamepad.XBOX = 2;
  72343. Gamepad.POSE_ENABLED = 3;
  72344. return Gamepad;
  72345. }());
  72346. BABYLON.Gamepad = Gamepad;
  72347. var GenericPad = /** @class */ (function (_super) {
  72348. __extends(GenericPad, _super);
  72349. function GenericPad(id, index, browserGamepad) {
  72350. var _this = _super.call(this, id, index, browserGamepad) || this;
  72351. _this.onButtonDownObservable = new BABYLON.Observable();
  72352. _this.onButtonUpObservable = new BABYLON.Observable();
  72353. _this.type = Gamepad.GENERIC;
  72354. _this._buttons = new Array(browserGamepad.buttons.length);
  72355. return _this;
  72356. }
  72357. GenericPad.prototype.onbuttondown = function (callback) {
  72358. this._onbuttondown = callback;
  72359. };
  72360. GenericPad.prototype.onbuttonup = function (callback) {
  72361. this._onbuttonup = callback;
  72362. };
  72363. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  72364. if (newValue !== currentValue) {
  72365. if (newValue === 1) {
  72366. if (this._onbuttondown) {
  72367. this._onbuttondown(buttonIndex);
  72368. }
  72369. this.onButtonDownObservable.notifyObservers(buttonIndex);
  72370. }
  72371. if (newValue === 0) {
  72372. if (this._onbuttonup) {
  72373. this._onbuttonup(buttonIndex);
  72374. }
  72375. this.onButtonUpObservable.notifyObservers(buttonIndex);
  72376. }
  72377. }
  72378. return newValue;
  72379. };
  72380. GenericPad.prototype.update = function () {
  72381. _super.prototype.update.call(this);
  72382. for (var index = 0; index < this._buttons.length; index++) {
  72383. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  72384. }
  72385. };
  72386. GenericPad.prototype.dispose = function () {
  72387. _super.prototype.dispose.call(this);
  72388. this.onButtonDownObservable.clear();
  72389. this.onButtonUpObservable.clear();
  72390. };
  72391. return GenericPad;
  72392. }(Gamepad));
  72393. BABYLON.GenericPad = GenericPad;
  72394. })(BABYLON || (BABYLON = {}));
  72395. //# sourceMappingURL=babylon.gamepad.js.map
  72396. var BABYLON;
  72397. (function (BABYLON) {
  72398. /**
  72399. * Defines supported buttons for XBox360 compatible gamepads
  72400. */
  72401. var Xbox360Button;
  72402. (function (Xbox360Button) {
  72403. /** A */
  72404. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  72405. /** B */
  72406. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  72407. /** X */
  72408. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  72409. /** Y */
  72410. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  72411. /** Start */
  72412. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  72413. /** Back */
  72414. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  72415. /** Left button */
  72416. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  72417. /** Right button */
  72418. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  72419. /** Left stick */
  72420. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  72421. /** Right stick */
  72422. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  72423. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  72424. /** Defines values for XBox360 DPad */
  72425. var Xbox360Dpad;
  72426. (function (Xbox360Dpad) {
  72427. /** Up */
  72428. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  72429. /** Down */
  72430. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  72431. /** Left */
  72432. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  72433. /** Right */
  72434. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  72435. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  72436. /**
  72437. * Defines a XBox360 gamepad
  72438. */
  72439. var Xbox360Pad = /** @class */ (function (_super) {
  72440. __extends(Xbox360Pad, _super);
  72441. /**
  72442. * Creates a new XBox360 gamepad object
  72443. * @param id defines the id of this gamepad
  72444. * @param index defines its index
  72445. * @param gamepad defines the internal HTML gamepad object
  72446. * @param xboxOne defines if it is a XBox One gamepad
  72447. */
  72448. function Xbox360Pad(id, index, gamepad, xboxOne) {
  72449. if (xboxOne === void 0) { xboxOne = false; }
  72450. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  72451. _this._leftTrigger = 0;
  72452. _this._rightTrigger = 0;
  72453. /** Observable raised when a button is pressed */
  72454. _this.onButtonDownObservable = new BABYLON.Observable();
  72455. /** Observable raised when a button is released */
  72456. _this.onButtonUpObservable = new BABYLON.Observable();
  72457. /** Observable raised when a pad is pressed */
  72458. _this.onPadDownObservable = new BABYLON.Observable();
  72459. /** Observable raised when a pad is released */
  72460. _this.onPadUpObservable = new BABYLON.Observable();
  72461. _this._buttonA = 0;
  72462. _this._buttonB = 0;
  72463. _this._buttonX = 0;
  72464. _this._buttonY = 0;
  72465. _this._buttonBack = 0;
  72466. _this._buttonStart = 0;
  72467. _this._buttonLB = 0;
  72468. _this._buttonRB = 0;
  72469. _this._buttonLeftStick = 0;
  72470. _this._buttonRightStick = 0;
  72471. _this._dPadUp = 0;
  72472. _this._dPadDown = 0;
  72473. _this._dPadLeft = 0;
  72474. _this._dPadRight = 0;
  72475. _this._isXboxOnePad = false;
  72476. _this.type = BABYLON.Gamepad.XBOX;
  72477. _this._isXboxOnePad = xboxOne;
  72478. return _this;
  72479. }
  72480. /**
  72481. * Defines the callback to call when left trigger is pressed
  72482. * @param callback defines the callback to use
  72483. */
  72484. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  72485. this._onlefttriggerchanged = callback;
  72486. };
  72487. /**
  72488. * Defines the callback to call when right trigger is pressed
  72489. * @param callback defines the callback to use
  72490. */
  72491. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  72492. this._onrighttriggerchanged = callback;
  72493. };
  72494. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  72495. /**
  72496. * Gets or sets left trigger value
  72497. */
  72498. get: function () {
  72499. return this._leftTrigger;
  72500. },
  72501. set: function (newValue) {
  72502. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  72503. this._onlefttriggerchanged(newValue);
  72504. }
  72505. this._leftTrigger = newValue;
  72506. },
  72507. enumerable: true,
  72508. configurable: true
  72509. });
  72510. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  72511. /**
  72512. * Gets or sets right trigger value
  72513. */
  72514. get: function () {
  72515. return this._rightTrigger;
  72516. },
  72517. set: function (newValue) {
  72518. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  72519. this._onrighttriggerchanged(newValue);
  72520. }
  72521. this._rightTrigger = newValue;
  72522. },
  72523. enumerable: true,
  72524. configurable: true
  72525. });
  72526. /**
  72527. * Defines the callback to call when a button is pressed
  72528. * @param callback defines the callback to use
  72529. */
  72530. Xbox360Pad.prototype.onbuttondown = function (callback) {
  72531. this._onbuttondown = callback;
  72532. };
  72533. /**
  72534. * Defines the callback to call when a button is released
  72535. * @param callback defines the callback to use
  72536. */
  72537. Xbox360Pad.prototype.onbuttonup = function (callback) {
  72538. this._onbuttonup = callback;
  72539. };
  72540. /**
  72541. * Defines the callback to call when a pad is pressed
  72542. * @param callback defines the callback to use
  72543. */
  72544. Xbox360Pad.prototype.ondpaddown = function (callback) {
  72545. this._ondpaddown = callback;
  72546. };
  72547. /**
  72548. * Defines the callback to call when a pad is released
  72549. * @param callback defines the callback to use
  72550. */
  72551. Xbox360Pad.prototype.ondpadup = function (callback) {
  72552. this._ondpadup = callback;
  72553. };
  72554. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  72555. if (newValue !== currentValue) {
  72556. if (newValue === 1) {
  72557. if (this._onbuttondown) {
  72558. this._onbuttondown(buttonType);
  72559. }
  72560. this.onButtonDownObservable.notifyObservers(buttonType);
  72561. }
  72562. if (newValue === 0) {
  72563. if (this._onbuttonup) {
  72564. this._onbuttonup(buttonType);
  72565. }
  72566. this.onButtonUpObservable.notifyObservers(buttonType);
  72567. }
  72568. }
  72569. return newValue;
  72570. };
  72571. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  72572. if (newValue !== currentValue) {
  72573. if (newValue === 1) {
  72574. if (this._ondpaddown) {
  72575. this._ondpaddown(buttonType);
  72576. }
  72577. this.onPadDownObservable.notifyObservers(buttonType);
  72578. }
  72579. if (newValue === 0) {
  72580. if (this._ondpadup) {
  72581. this._ondpadup(buttonType);
  72582. }
  72583. this.onPadUpObservable.notifyObservers(buttonType);
  72584. }
  72585. }
  72586. return newValue;
  72587. };
  72588. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  72589. /** Gets or sets value of A button */
  72590. get: function () {
  72591. return this._buttonA;
  72592. },
  72593. set: function (value) {
  72594. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  72595. },
  72596. enumerable: true,
  72597. configurable: true
  72598. });
  72599. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  72600. /** Gets or sets value of B button */
  72601. get: function () {
  72602. return this._buttonB;
  72603. },
  72604. set: function (value) {
  72605. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  72606. },
  72607. enumerable: true,
  72608. configurable: true
  72609. });
  72610. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  72611. /** Gets or sets value of X button */
  72612. get: function () {
  72613. return this._buttonX;
  72614. },
  72615. set: function (value) {
  72616. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  72617. },
  72618. enumerable: true,
  72619. configurable: true
  72620. });
  72621. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  72622. /** Gets or sets value of Y button */
  72623. get: function () {
  72624. return this._buttonY;
  72625. },
  72626. set: function (value) {
  72627. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  72628. },
  72629. enumerable: true,
  72630. configurable: true
  72631. });
  72632. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  72633. /** Gets or sets value of Start button */
  72634. get: function () {
  72635. return this._buttonStart;
  72636. },
  72637. set: function (value) {
  72638. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  72639. },
  72640. enumerable: true,
  72641. configurable: true
  72642. });
  72643. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  72644. /** Gets or sets value of Back button */
  72645. get: function () {
  72646. return this._buttonBack;
  72647. },
  72648. set: function (value) {
  72649. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  72650. },
  72651. enumerable: true,
  72652. configurable: true
  72653. });
  72654. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  72655. /** Gets or sets value of Left button */
  72656. get: function () {
  72657. return this._buttonLB;
  72658. },
  72659. set: function (value) {
  72660. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  72661. },
  72662. enumerable: true,
  72663. configurable: true
  72664. });
  72665. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  72666. /** Gets or sets value of Right button */
  72667. get: function () {
  72668. return this._buttonRB;
  72669. },
  72670. set: function (value) {
  72671. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  72672. },
  72673. enumerable: true,
  72674. configurable: true
  72675. });
  72676. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  72677. /** Gets or sets value of left stick */
  72678. get: function () {
  72679. return this._buttonLeftStick;
  72680. },
  72681. set: function (value) {
  72682. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  72683. },
  72684. enumerable: true,
  72685. configurable: true
  72686. });
  72687. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  72688. /** Gets or sets value of right stick */
  72689. get: function () {
  72690. return this._buttonRightStick;
  72691. },
  72692. set: function (value) {
  72693. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  72694. },
  72695. enumerable: true,
  72696. configurable: true
  72697. });
  72698. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  72699. /** Gets or sets value of DPad up */
  72700. get: function () {
  72701. return this._dPadUp;
  72702. },
  72703. set: function (value) {
  72704. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  72705. },
  72706. enumerable: true,
  72707. configurable: true
  72708. });
  72709. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  72710. /** Gets or sets value of DPad down */
  72711. get: function () {
  72712. return this._dPadDown;
  72713. },
  72714. set: function (value) {
  72715. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  72716. },
  72717. enumerable: true,
  72718. configurable: true
  72719. });
  72720. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  72721. /** Gets or sets value of DPad left */
  72722. get: function () {
  72723. return this._dPadLeft;
  72724. },
  72725. set: function (value) {
  72726. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  72727. },
  72728. enumerable: true,
  72729. configurable: true
  72730. });
  72731. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  72732. /** Gets or sets value of DPad right */
  72733. get: function () {
  72734. return this._dPadRight;
  72735. },
  72736. set: function (value) {
  72737. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  72738. },
  72739. enumerable: true,
  72740. configurable: true
  72741. });
  72742. /**
  72743. * Force the gamepad to synchronize with device values
  72744. */
  72745. Xbox360Pad.prototype.update = function () {
  72746. _super.prototype.update.call(this);
  72747. if (this._isXboxOnePad) {
  72748. this.buttonA = this.browserGamepad.buttons[0].value;
  72749. this.buttonB = this.browserGamepad.buttons[1].value;
  72750. this.buttonX = this.browserGamepad.buttons[2].value;
  72751. this.buttonY = this.browserGamepad.buttons[3].value;
  72752. this.buttonLB = this.browserGamepad.buttons[4].value;
  72753. this.buttonRB = this.browserGamepad.buttons[5].value;
  72754. this.leftTrigger = this.browserGamepad.axes[2];
  72755. this.rightTrigger = this.browserGamepad.axes[5];
  72756. this.buttonBack = this.browserGamepad.buttons[9].value;
  72757. this.buttonStart = this.browserGamepad.buttons[8].value;
  72758. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  72759. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  72760. this.dPadUp = this.browserGamepad.buttons[11].value;
  72761. this.dPadDown = this.browserGamepad.buttons[12].value;
  72762. this.dPadLeft = this.browserGamepad.buttons[13].value;
  72763. this.dPadRight = this.browserGamepad.buttons[14].value;
  72764. }
  72765. else {
  72766. this.buttonA = this.browserGamepad.buttons[0].value;
  72767. this.buttonB = this.browserGamepad.buttons[1].value;
  72768. this.buttonX = this.browserGamepad.buttons[2].value;
  72769. this.buttonY = this.browserGamepad.buttons[3].value;
  72770. this.buttonLB = this.browserGamepad.buttons[4].value;
  72771. this.buttonRB = this.browserGamepad.buttons[5].value;
  72772. this.leftTrigger = this.browserGamepad.buttons[6].value;
  72773. this.rightTrigger = this.browserGamepad.buttons[7].value;
  72774. this.buttonBack = this.browserGamepad.buttons[8].value;
  72775. this.buttonStart = this.browserGamepad.buttons[9].value;
  72776. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  72777. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  72778. this.dPadUp = this.browserGamepad.buttons[12].value;
  72779. this.dPadDown = this.browserGamepad.buttons[13].value;
  72780. this.dPadLeft = this.browserGamepad.buttons[14].value;
  72781. this.dPadRight = this.browserGamepad.buttons[15].value;
  72782. }
  72783. };
  72784. Xbox360Pad.prototype.dispose = function () {
  72785. _super.prototype.dispose.call(this);
  72786. this.onButtonDownObservable.clear();
  72787. this.onButtonUpObservable.clear();
  72788. this.onPadDownObservable.clear();
  72789. this.onPadUpObservable.clear();
  72790. };
  72791. return Xbox360Pad;
  72792. }(BABYLON.Gamepad));
  72793. BABYLON.Xbox360Pad = Xbox360Pad;
  72794. })(BABYLON || (BABYLON = {}));
  72795. //# sourceMappingURL=babylon.xboxGamepad.js.map
  72796. var BABYLON;
  72797. (function (BABYLON) {
  72798. /**
  72799. * Defines the types of pose enabled controllers that are supported
  72800. */
  72801. var PoseEnabledControllerType;
  72802. (function (PoseEnabledControllerType) {
  72803. /**
  72804. * HTC Vive
  72805. */
  72806. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  72807. /**
  72808. * Oculus Rift
  72809. */
  72810. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  72811. /**
  72812. * Windows mixed reality
  72813. */
  72814. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  72815. /**
  72816. * Samsung gear VR
  72817. */
  72818. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  72819. /**
  72820. * Google Daydream
  72821. */
  72822. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  72823. /**
  72824. * Generic
  72825. */
  72826. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  72827. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  72828. /**
  72829. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72830. */
  72831. var PoseEnabledControllerHelper = /** @class */ (function () {
  72832. function PoseEnabledControllerHelper() {
  72833. }
  72834. /**
  72835. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72836. * @param vrGamepad the gamepad to initialized
  72837. * @returns a vr controller of the type the gamepad identified as
  72838. */
  72839. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  72840. // Oculus Touch
  72841. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  72842. return new BABYLON.OculusTouchController(vrGamepad);
  72843. }
  72844. // Windows Mixed Reality controllers
  72845. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  72846. return new BABYLON.WindowsMotionController(vrGamepad);
  72847. }
  72848. // HTC Vive
  72849. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  72850. return new BABYLON.ViveController(vrGamepad);
  72851. }
  72852. // Samsung/Oculus Gear VR or Oculus Go
  72853. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  72854. return new BABYLON.GearVRController(vrGamepad);
  72855. }
  72856. // Google Daydream
  72857. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  72858. return new BABYLON.DaydreamController(vrGamepad);
  72859. }
  72860. // Generic
  72861. else {
  72862. return new BABYLON.GenericController(vrGamepad);
  72863. }
  72864. };
  72865. return PoseEnabledControllerHelper;
  72866. }());
  72867. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  72868. /**
  72869. * Defines the PoseEnabledController object that contains state of a vr capable controller
  72870. */
  72871. var PoseEnabledController = /** @class */ (function (_super) {
  72872. __extends(PoseEnabledController, _super);
  72873. /**
  72874. * Creates a new PoseEnabledController from a gamepad
  72875. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  72876. */
  72877. function PoseEnabledController(browserGamepad) {
  72878. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  72879. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72880. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72881. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  72882. /**
  72883. * The device position in babylon space
  72884. */
  72885. _this.devicePosition = BABYLON.Vector3.Zero();
  72886. /**
  72887. * The device rotation in babylon space
  72888. */
  72889. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  72890. /**
  72891. * The scale factor of the device in babylon space
  72892. */
  72893. _this.deviceScaleFactor = 1;
  72894. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  72895. /**
  72896. * Internal, matrix used to convert room space to babylon space
  72897. */
  72898. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72899. /**
  72900. * Node to be used when casting a ray from the controller
  72901. */
  72902. _this._pointingPoseNode = null;
  72903. _this._workingMatrix = BABYLON.Matrix.Identity();
  72904. /**
  72905. * @hidden
  72906. */
  72907. _this._meshAttachedObservable = new BABYLON.Observable();
  72908. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  72909. _this.controllerType = PoseEnabledControllerType.GENERIC;
  72910. _this.position = BABYLON.Vector3.Zero();
  72911. _this.rotationQuaternion = new BABYLON.Quaternion();
  72912. _this._calculatedPosition = BABYLON.Vector3.Zero();
  72913. _this._calculatedRotation = new BABYLON.Quaternion();
  72914. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  72915. return _this;
  72916. }
  72917. /**
  72918. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  72919. */
  72920. PoseEnabledController.prototype.update = function () {
  72921. _super.prototype.update.call(this);
  72922. this._updatePoseAndMesh();
  72923. };
  72924. /**
  72925. * Updates only the pose device and mesh without doing any button event checking
  72926. */
  72927. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  72928. var pose = this.browserGamepad.pose;
  72929. this.updateFromDevice(pose);
  72930. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  72931. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  72932. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72933. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  72934. if (this._mesh) {
  72935. this._mesh.position.copyFrom(this.devicePosition);
  72936. if (this._mesh.rotationQuaternion) {
  72937. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  72938. }
  72939. }
  72940. };
  72941. /**
  72942. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72943. * @param poseData raw pose fromthe device
  72944. */
  72945. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  72946. if (poseData) {
  72947. this.rawPose = poseData;
  72948. if (poseData.position) {
  72949. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  72950. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  72951. this._deviceRoomPosition.z *= -1;
  72952. }
  72953. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  72954. this._calculatedPosition.addInPlace(this.position);
  72955. }
  72956. var pose = this.rawPose;
  72957. if (poseData.orientation && pose.orientation) {
  72958. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  72959. if (this._mesh) {
  72960. if (this._mesh.getScene().useRightHandedSystem) {
  72961. this._deviceRoomRotationQuaternion.z *= -1;
  72962. this._deviceRoomRotationQuaternion.w *= -1;
  72963. }
  72964. else {
  72965. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  72966. }
  72967. }
  72968. // if the camera is set, rotate to the camera's rotation
  72969. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  72970. }
  72971. }
  72972. };
  72973. /**
  72974. * Attaches a mesh to the controller
  72975. * @param mesh the mesh to be attached
  72976. */
  72977. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  72978. if (this._mesh) {
  72979. this._mesh.parent = null;
  72980. }
  72981. this._mesh = mesh;
  72982. if (this._poseControlledCamera) {
  72983. this._mesh.parent = this._poseControlledCamera;
  72984. }
  72985. if (!this._mesh.rotationQuaternion) {
  72986. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  72987. }
  72988. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  72989. this._updatePoseAndMesh();
  72990. if (this._pointingPoseNode) {
  72991. var parents = [];
  72992. var obj = this._pointingPoseNode;
  72993. while (obj.parent) {
  72994. parents.push(obj.parent);
  72995. obj = obj.parent;
  72996. }
  72997. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  72998. }
  72999. this._meshAttachedObservable.notifyObservers(mesh);
  73000. };
  73001. /**
  73002. * Attaches the controllers mesh to a camera
  73003. * @param camera the camera the mesh should be attached to
  73004. */
  73005. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  73006. this._poseControlledCamera = camera;
  73007. if (this._mesh) {
  73008. this._mesh.parent = this._poseControlledCamera;
  73009. }
  73010. };
  73011. /**
  73012. * Disposes of the controller
  73013. */
  73014. PoseEnabledController.prototype.dispose = function () {
  73015. if (this._mesh) {
  73016. this._mesh.dispose();
  73017. }
  73018. this._mesh = null;
  73019. _super.prototype.dispose.call(this);
  73020. };
  73021. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  73022. /**
  73023. * The mesh that is attached to the controller
  73024. */
  73025. get: function () {
  73026. return this._mesh;
  73027. },
  73028. enumerable: true,
  73029. configurable: true
  73030. });
  73031. /**
  73032. * Gets the ray of the controller in the direction the controller is pointing
  73033. * @param length the length the resulting ray should be
  73034. * @returns a ray in the direction the controller is pointing
  73035. */
  73036. PoseEnabledController.prototype.getForwardRay = function (length) {
  73037. if (length === void 0) { length = 100; }
  73038. if (!this.mesh) {
  73039. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  73040. }
  73041. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  73042. var origin = m.getTranslation();
  73043. var forward = new BABYLON.Vector3(0, 0, -1);
  73044. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73045. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73046. return new BABYLON.Ray(origin, direction, length);
  73047. };
  73048. /**
  73049. * Name of the child mesh that can be used to cast a ray from the controller
  73050. */
  73051. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  73052. return PoseEnabledController;
  73053. }(BABYLON.Gamepad));
  73054. BABYLON.PoseEnabledController = PoseEnabledController;
  73055. })(BABYLON || (BABYLON = {}));
  73056. //# sourceMappingURL=babylon.poseEnabledController.js.map
  73057. var BABYLON;
  73058. (function (BABYLON) {
  73059. /**
  73060. * Defines the WebVRController object that represents controllers tracked in 3D space
  73061. */
  73062. var WebVRController = /** @class */ (function (_super) {
  73063. __extends(WebVRController, _super);
  73064. /**
  73065. * Creates a new WebVRController from a gamepad
  73066. * @param vrGamepad the gamepad that the WebVRController should be created from
  73067. */
  73068. function WebVRController(vrGamepad) {
  73069. var _this = _super.call(this, vrGamepad) || this;
  73070. // Observables
  73071. /**
  73072. * Fired when the trigger state has changed
  73073. */
  73074. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  73075. /**
  73076. * Fired when the main button state has changed
  73077. */
  73078. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  73079. /**
  73080. * Fired when the secondary button state has changed
  73081. */
  73082. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  73083. /**
  73084. * Fired when the pad state has changed
  73085. */
  73086. _this.onPadStateChangedObservable = new BABYLON.Observable();
  73087. /**
  73088. * Fired when controllers stick values have changed
  73089. */
  73090. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  73091. /**
  73092. * X and Y axis corrisponding to the controllers joystick
  73093. */
  73094. _this.pad = { x: 0, y: 0 };
  73095. // avoid GC, store state in a tmp object
  73096. _this._changes = {
  73097. pressChanged: false,
  73098. touchChanged: false,
  73099. valueChanged: false,
  73100. changed: false
  73101. };
  73102. _this._buttons = new Array(vrGamepad.buttons.length);
  73103. _this.hand = vrGamepad.hand;
  73104. return _this;
  73105. }
  73106. /**
  73107. * Fired when a controller button's state has changed
  73108. * @param callback the callback containing the button that was modified
  73109. */
  73110. WebVRController.prototype.onButtonStateChange = function (callback) {
  73111. this._onButtonStateChange = callback;
  73112. };
  73113. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  73114. /**
  73115. * The default controller model for the controller
  73116. */
  73117. get: function () {
  73118. return this._defaultModel;
  73119. },
  73120. enumerable: true,
  73121. configurable: true
  73122. });
  73123. /**
  73124. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  73125. */
  73126. WebVRController.prototype.update = function () {
  73127. _super.prototype.update.call(this);
  73128. for (var index = 0; index < this._buttons.length; index++) {
  73129. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  73130. }
  73131. ;
  73132. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  73133. this.pad.x = this.leftStick.x;
  73134. this.pad.y = this.leftStick.y;
  73135. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  73136. }
  73137. };
  73138. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  73139. if (!newState) {
  73140. newState = {
  73141. pressed: false,
  73142. touched: false,
  73143. value: 0
  73144. };
  73145. }
  73146. if (!currentState) {
  73147. this._buttons[buttonIndex] = {
  73148. pressed: newState.pressed,
  73149. touched: newState.touched,
  73150. value: newState.value
  73151. };
  73152. return;
  73153. }
  73154. this._checkChanges(newState, currentState);
  73155. if (this._changes.changed) {
  73156. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  73157. this._handleButtonChange(buttonIndex, newState, this._changes);
  73158. }
  73159. this._buttons[buttonIndex].pressed = newState.pressed;
  73160. this._buttons[buttonIndex].touched = newState.touched;
  73161. // oculus triggers are never 0, thou not touched.
  73162. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  73163. };
  73164. WebVRController.prototype._checkChanges = function (newState, currentState) {
  73165. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  73166. this._changes.touchChanged = newState.touched !== currentState.touched;
  73167. this._changes.valueChanged = newState.value !== currentState.value;
  73168. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  73169. return this._changes;
  73170. };
  73171. /**
  73172. * Disposes of th webVRCOntroller
  73173. */
  73174. WebVRController.prototype.dispose = function () {
  73175. _super.prototype.dispose.call(this);
  73176. this.onTriggerStateChangedObservable.clear();
  73177. this.onMainButtonStateChangedObservable.clear();
  73178. this.onSecondaryButtonStateChangedObservable.clear();
  73179. this.onPadStateChangedObservable.clear();
  73180. this.onPadValuesChangedObservable.clear();
  73181. };
  73182. return WebVRController;
  73183. }(BABYLON.PoseEnabledController));
  73184. BABYLON.WebVRController = WebVRController;
  73185. })(BABYLON || (BABYLON = {}));
  73186. //# sourceMappingURL=babylon.webVRController.js.map
  73187. var BABYLON;
  73188. (function (BABYLON) {
  73189. /**
  73190. * Oculus Touch Controller
  73191. */
  73192. var OculusTouchController = /** @class */ (function (_super) {
  73193. __extends(OculusTouchController, _super);
  73194. /**
  73195. * Creates a new OculusTouchController from a gamepad
  73196. * @param vrGamepad the gamepad that the controller should be created from
  73197. */
  73198. function OculusTouchController(vrGamepad) {
  73199. var _this = _super.call(this, vrGamepad) || this;
  73200. /**
  73201. * Fired when the secondary trigger on this controller is modified
  73202. */
  73203. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  73204. /**
  73205. * Fired when the thumb rest on this controller is modified
  73206. */
  73207. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  73208. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  73209. return _this;
  73210. }
  73211. /**
  73212. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73213. * @param scene scene in which to add meshes
  73214. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73215. */
  73216. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73217. var _this = this;
  73218. var meshName;
  73219. // Hand
  73220. if (this.hand === 'left') {
  73221. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  73222. }
  73223. else { // Right is the default if no hand is specified
  73224. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  73225. }
  73226. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  73227. /*
  73228. Parent Mesh name: oculus_touch_left
  73229. - body
  73230. - trigger
  73231. - thumbstick
  73232. - grip
  73233. - button_y
  73234. - button_x
  73235. - button_enter
  73236. */
  73237. _this._defaultModel = newMeshes[1];
  73238. _this.attachToMesh(_this._defaultModel);
  73239. if (meshLoaded) {
  73240. meshLoaded(_this._defaultModel);
  73241. }
  73242. });
  73243. };
  73244. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  73245. /**
  73246. * Fired when the A button on this controller is modified
  73247. */
  73248. get: function () {
  73249. if (this.hand === 'right') {
  73250. return this.onMainButtonStateChangedObservable;
  73251. }
  73252. else {
  73253. throw new Error('No A button on left hand');
  73254. }
  73255. },
  73256. enumerable: true,
  73257. configurable: true
  73258. });
  73259. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  73260. /**
  73261. * Fired when the B button on this controller is modified
  73262. */
  73263. get: function () {
  73264. if (this.hand === 'right') {
  73265. return this.onSecondaryButtonStateChangedObservable;
  73266. }
  73267. else {
  73268. throw new Error('No B button on left hand');
  73269. }
  73270. },
  73271. enumerable: true,
  73272. configurable: true
  73273. });
  73274. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  73275. /**
  73276. * Fired when the X button on this controller is modified
  73277. */
  73278. get: function () {
  73279. if (this.hand === 'left') {
  73280. return this.onMainButtonStateChangedObservable;
  73281. }
  73282. else {
  73283. throw new Error('No X button on right hand');
  73284. }
  73285. },
  73286. enumerable: true,
  73287. configurable: true
  73288. });
  73289. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  73290. /**
  73291. * Fired when the Y button on this controller is modified
  73292. */
  73293. get: function () {
  73294. if (this.hand === 'left') {
  73295. return this.onSecondaryButtonStateChangedObservable;
  73296. }
  73297. else {
  73298. throw new Error('No Y button on right hand');
  73299. }
  73300. },
  73301. enumerable: true,
  73302. configurable: true
  73303. });
  73304. /**
  73305. * Called once for each button that changed state since the last frame
  73306. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  73307. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  73308. * 2) secondary trigger (same)
  73309. * 3) A (right) X (left), touch, pressed = value
  73310. * 4) B / Y
  73311. * 5) thumb rest
  73312. * @param buttonIdx Which button index changed
  73313. * @param state New state of the button
  73314. * @param changes Which properties on the state changed since last frame
  73315. */
  73316. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73317. var notifyObject = state; //{ state: state, changes: changes };
  73318. var triggerDirection = this.hand === 'right' ? -1 : 1;
  73319. switch (buttonIdx) {
  73320. case 0:
  73321. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73322. return;
  73323. case 1: // index trigger
  73324. if (this._defaultModel) {
  73325. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  73326. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  73327. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  73328. }
  73329. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73330. return;
  73331. case 2: // secondary trigger
  73332. if (this._defaultModel) {
  73333. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  73334. }
  73335. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  73336. return;
  73337. case 3:
  73338. if (this._defaultModel) {
  73339. if (notifyObject.pressed) {
  73340. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  73341. }
  73342. else {
  73343. (this._defaultModel.getChildren()[1]).position.y = 0;
  73344. }
  73345. }
  73346. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73347. return;
  73348. case 4:
  73349. if (this._defaultModel) {
  73350. if (notifyObject.pressed) {
  73351. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73352. }
  73353. else {
  73354. (this._defaultModel.getChildren()[2]).position.y = 0;
  73355. }
  73356. }
  73357. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73358. return;
  73359. case 5:
  73360. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  73361. return;
  73362. }
  73363. };
  73364. /**
  73365. * Base Url for the controller model.
  73366. */
  73367. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  73368. /**
  73369. * File name for the left controller model.
  73370. */
  73371. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  73372. /**
  73373. * File name for the right controller model.
  73374. */
  73375. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  73376. return OculusTouchController;
  73377. }(BABYLON.WebVRController));
  73378. BABYLON.OculusTouchController = OculusTouchController;
  73379. })(BABYLON || (BABYLON = {}));
  73380. //# sourceMappingURL=babylon.oculusTouchController.js.map
  73381. var BABYLON;
  73382. (function (BABYLON) {
  73383. /**
  73384. * Vive Controller
  73385. */
  73386. var ViveController = /** @class */ (function (_super) {
  73387. __extends(ViveController, _super);
  73388. /**
  73389. * Creates a new ViveController from a gamepad
  73390. * @param vrGamepad the gamepad that the controller should be created from
  73391. */
  73392. function ViveController(vrGamepad) {
  73393. var _this = _super.call(this, vrGamepad) || this;
  73394. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  73395. _this._invertLeftStickY = true;
  73396. return _this;
  73397. }
  73398. /**
  73399. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73400. * @param scene scene in which to add meshes
  73401. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73402. */
  73403. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73404. var _this = this;
  73405. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  73406. /*
  73407. Parent Mesh name: ViveWand
  73408. - body
  73409. - r_gripper
  73410. - l_gripper
  73411. - menu_button
  73412. - system_button
  73413. - trackpad
  73414. - trigger
  73415. - LED
  73416. */
  73417. _this._defaultModel = newMeshes[1];
  73418. _this.attachToMesh(_this._defaultModel);
  73419. if (meshLoaded) {
  73420. meshLoaded(_this._defaultModel);
  73421. }
  73422. });
  73423. };
  73424. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  73425. /**
  73426. * Fired when the left button on this controller is modified
  73427. */
  73428. get: function () {
  73429. return this.onMainButtonStateChangedObservable;
  73430. },
  73431. enumerable: true,
  73432. configurable: true
  73433. });
  73434. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  73435. /**
  73436. * Fired when the right button on this controller is modified
  73437. */
  73438. get: function () {
  73439. return this.onMainButtonStateChangedObservable;
  73440. },
  73441. enumerable: true,
  73442. configurable: true
  73443. });
  73444. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  73445. /**
  73446. * Fired when the menu button on this controller is modified
  73447. */
  73448. get: function () {
  73449. return this.onSecondaryButtonStateChangedObservable;
  73450. },
  73451. enumerable: true,
  73452. configurable: true
  73453. });
  73454. /**
  73455. * Called once for each button that changed state since the last frame
  73456. * Vive mapping:
  73457. * 0: touchpad
  73458. * 1: trigger
  73459. * 2: left AND right buttons
  73460. * 3: menu button
  73461. * @param buttonIdx Which button index changed
  73462. * @param state New state of the button
  73463. * @param changes Which properties on the state changed since last frame
  73464. */
  73465. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73466. var notifyObject = state; //{ state: state, changes: changes };
  73467. switch (buttonIdx) {
  73468. case 0:
  73469. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73470. return;
  73471. case 1: // index trigger
  73472. if (this._defaultModel) {
  73473. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  73474. }
  73475. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73476. return;
  73477. case 2: // left AND right button
  73478. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73479. return;
  73480. case 3:
  73481. if (this._defaultModel) {
  73482. if (notifyObject.pressed) {
  73483. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73484. }
  73485. else {
  73486. (this._defaultModel.getChildren()[2]).position.y = 0;
  73487. }
  73488. }
  73489. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73490. return;
  73491. }
  73492. };
  73493. /**
  73494. * Base Url for the controller model.
  73495. */
  73496. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  73497. /**
  73498. * File name for the controller model.
  73499. */
  73500. ViveController.MODEL_FILENAME = 'wand.babylon';
  73501. return ViveController;
  73502. }(BABYLON.WebVRController));
  73503. BABYLON.ViveController = ViveController;
  73504. })(BABYLON || (BABYLON = {}));
  73505. //# sourceMappingURL=babylon.viveController.js.map
  73506. var BABYLON;
  73507. (function (BABYLON) {
  73508. /**
  73509. * Generic Controller
  73510. */
  73511. var GenericController = /** @class */ (function (_super) {
  73512. __extends(GenericController, _super);
  73513. /**
  73514. * Creates a new GenericController from a gamepad
  73515. * @param vrGamepad the gamepad that the controller should be created from
  73516. */
  73517. function GenericController(vrGamepad) {
  73518. return _super.call(this, vrGamepad) || this;
  73519. }
  73520. /**
  73521. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73522. * @param scene scene in which to add meshes
  73523. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73524. */
  73525. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73526. var _this = this;
  73527. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  73528. _this._defaultModel = newMeshes[1];
  73529. _this.attachToMesh(_this._defaultModel);
  73530. if (meshLoaded) {
  73531. meshLoaded(_this._defaultModel);
  73532. }
  73533. });
  73534. };
  73535. /**
  73536. * Called once for each button that changed state since the last frame
  73537. * @param buttonIdx Which button index changed
  73538. * @param state New state of the button
  73539. * @param changes Which properties on the state changed since last frame
  73540. */
  73541. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73542. console.log("Button id: " + buttonIdx + "state: ");
  73543. console.dir(state);
  73544. };
  73545. /**
  73546. * Base Url for the controller model.
  73547. */
  73548. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73549. /**
  73550. * File name for the controller model.
  73551. */
  73552. GenericController.MODEL_FILENAME = 'generic.babylon';
  73553. return GenericController;
  73554. }(BABYLON.WebVRController));
  73555. BABYLON.GenericController = GenericController;
  73556. })(BABYLON || (BABYLON = {}));
  73557. //# sourceMappingURL=babylon.genericController.js.map
  73558. var BABYLON;
  73559. (function (BABYLON) {
  73560. /**
  73561. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  73562. */
  73563. var LoadedMeshInfo = /** @class */ (function () {
  73564. function LoadedMeshInfo() {
  73565. /**
  73566. * Map of the button meshes contained in the controller
  73567. */
  73568. this.buttonMeshes = {};
  73569. /**
  73570. * Map of the axis meshes contained in the controller
  73571. */
  73572. this.axisMeshes = {};
  73573. }
  73574. return LoadedMeshInfo;
  73575. }());
  73576. /**
  73577. * Defines the WindowsMotionController object that the state of the windows motion controller
  73578. */
  73579. var WindowsMotionController = /** @class */ (function (_super) {
  73580. __extends(WindowsMotionController, _super);
  73581. /**
  73582. * Creates a new WindowsMotionController from a gamepad
  73583. * @param vrGamepad the gamepad that the controller should be created from
  73584. */
  73585. function WindowsMotionController(vrGamepad) {
  73586. var _this = _super.call(this, vrGamepad) || this;
  73587. _this._mapping = {
  73588. // Semantic button names
  73589. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  73590. // A mapping of the button name to glTF model node name
  73591. // that should be transformed by button value.
  73592. buttonMeshNames: {
  73593. 'trigger': 'SELECT',
  73594. 'menu': 'MENU',
  73595. 'grip': 'GRASP',
  73596. 'thumbstick': 'THUMBSTICK_PRESS',
  73597. 'trackpad': 'TOUCHPAD_PRESS'
  73598. },
  73599. // This mapping is used to translate from the Motion Controller to Babylon semantics
  73600. buttonObservableNames: {
  73601. 'trigger': 'onTriggerStateChangedObservable',
  73602. 'menu': 'onSecondaryButtonStateChangedObservable',
  73603. 'grip': 'onMainButtonStateChangedObservable',
  73604. 'thumbstick': 'onPadStateChangedObservable',
  73605. 'trackpad': 'onTrackpadChangedObservable'
  73606. },
  73607. // A mapping of the axis name to glTF model node name
  73608. // that should be transformed by axis value.
  73609. // This array mirrors the browserGamepad.axes array, such that
  73610. // the mesh corresponding to axis 0 is in this array index 0.
  73611. axisMeshNames: [
  73612. 'THUMBSTICK_X',
  73613. 'THUMBSTICK_Y',
  73614. 'TOUCHPAD_TOUCH_X',
  73615. 'TOUCHPAD_TOUCH_Y'
  73616. ],
  73617. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  73618. };
  73619. /**
  73620. * Fired when the trackpad on this controller is clicked
  73621. */
  73622. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  73623. /**
  73624. * Fired when the trackpad on this controller is modified
  73625. */
  73626. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  73627. /**
  73628. * The current x and y values of this controller's trackpad
  73629. */
  73630. _this.trackpad = { x: 0, y: 0 };
  73631. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  73632. _this._loadedMeshInfo = null;
  73633. return _this;
  73634. }
  73635. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  73636. /**
  73637. * Fired when the trigger on this controller is modified
  73638. */
  73639. get: function () {
  73640. return this.onTriggerStateChangedObservable;
  73641. },
  73642. enumerable: true,
  73643. configurable: true
  73644. });
  73645. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  73646. /**
  73647. * Fired when the menu button on this controller is modified
  73648. */
  73649. get: function () {
  73650. return this.onSecondaryButtonStateChangedObservable;
  73651. },
  73652. enumerable: true,
  73653. configurable: true
  73654. });
  73655. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  73656. /**
  73657. * Fired when the grip button on this controller is modified
  73658. */
  73659. get: function () {
  73660. return this.onMainButtonStateChangedObservable;
  73661. },
  73662. enumerable: true,
  73663. configurable: true
  73664. });
  73665. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  73666. /**
  73667. * Fired when the thumbstick button on this controller is modified
  73668. */
  73669. get: function () {
  73670. return this.onPadStateChangedObservable;
  73671. },
  73672. enumerable: true,
  73673. configurable: true
  73674. });
  73675. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  73676. /**
  73677. * Fired when the touchpad button on this controller is modified
  73678. */
  73679. get: function () {
  73680. return this.onTrackpadChangedObservable;
  73681. },
  73682. enumerable: true,
  73683. configurable: true
  73684. });
  73685. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  73686. /**
  73687. * Fired when the touchpad values on this controller are modified
  73688. */
  73689. get: function () {
  73690. return this.onTrackpadValuesChangedObservable;
  73691. },
  73692. enumerable: true,
  73693. configurable: true
  73694. });
  73695. WindowsMotionController.prototype._updateTrackpad = function () {
  73696. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  73697. this.trackpad.x = this.browserGamepad["axes"][2];
  73698. this.trackpad.y = this.browserGamepad["axes"][3];
  73699. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  73700. }
  73701. };
  73702. /**
  73703. * Called once per frame by the engine.
  73704. */
  73705. WindowsMotionController.prototype.update = function () {
  73706. _super.prototype.update.call(this);
  73707. if (this.browserGamepad.axes) {
  73708. this._updateTrackpad();
  73709. // Only need to animate axes if there is a loaded mesh
  73710. if (this._loadedMeshInfo) {
  73711. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  73712. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  73713. }
  73714. }
  73715. }
  73716. };
  73717. /**
  73718. * Called once for each button that changed state since the last frame
  73719. * @param buttonIdx Which button index changed
  73720. * @param state New state of the button
  73721. * @param changes Which properties on the state changed since last frame
  73722. */
  73723. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73724. var buttonName = this._mapping.buttons[buttonIdx];
  73725. if (!buttonName) {
  73726. return;
  73727. }
  73728. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  73729. this._updateTrackpad();
  73730. // Only emit events for buttons that we know how to map from index to name
  73731. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  73732. if (observable) {
  73733. observable.notifyObservers(state);
  73734. }
  73735. this._lerpButtonTransform(buttonName, state.value);
  73736. };
  73737. /**
  73738. * Moves the buttons on the controller mesh based on their current state
  73739. * @param buttonName the name of the button to move
  73740. * @param buttonValue the value of the button which determines the buttons new position
  73741. */
  73742. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  73743. // If there is no loaded mesh, there is nothing to transform.
  73744. if (!this._loadedMeshInfo) {
  73745. return;
  73746. }
  73747. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  73748. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73749. return;
  73750. }
  73751. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  73752. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  73753. };
  73754. /**
  73755. * Moves the axis on the controller mesh based on its current state
  73756. * @param axis the index of the axis
  73757. * @param axisValue the value of the axis which determines the meshes new position
  73758. * @hidden
  73759. */
  73760. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  73761. if (!this._loadedMeshInfo) {
  73762. return;
  73763. }
  73764. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  73765. if (!meshInfo) {
  73766. return;
  73767. }
  73768. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73769. return;
  73770. }
  73771. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  73772. var lerpValue = axisValue * 0.5 + 0.5;
  73773. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  73774. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  73775. };
  73776. /**
  73777. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73778. * @param scene scene in which to add meshes
  73779. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73780. */
  73781. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  73782. var _this = this;
  73783. if (forceDefault === void 0) { forceDefault = false; }
  73784. var path;
  73785. var filename;
  73786. // Checking if GLB loader is present
  73787. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  73788. // Determine the device specific folder based on the ID suffix
  73789. var device = 'default';
  73790. if (this.id && !forceDefault) {
  73791. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  73792. device = ((match && match[0]) || device);
  73793. }
  73794. // Hand
  73795. if (this.hand === 'left') {
  73796. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  73797. }
  73798. else { // Right is the default if no hand is specified
  73799. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  73800. }
  73801. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  73802. }
  73803. else {
  73804. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  73805. path = BABYLON.GenericController.MODEL_BASE_URL;
  73806. filename = BABYLON.GenericController.MODEL_FILENAME;
  73807. }
  73808. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  73809. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  73810. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  73811. if (!_this._loadedMeshInfo) {
  73812. return;
  73813. }
  73814. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  73815. _this.attachToMesh(_this._defaultModel);
  73816. if (meshLoaded) {
  73817. meshLoaded(_this._defaultModel);
  73818. }
  73819. }, null, function (scene, message) {
  73820. BABYLON.Tools.Log(message);
  73821. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  73822. if (!forceDefault) {
  73823. _this.initControllerMesh(scene, meshLoaded, true);
  73824. }
  73825. });
  73826. };
  73827. /**
  73828. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  73829. * can be transformed by button presses and axes values, based on this._mapping.
  73830. *
  73831. * @param scene scene in which the meshes exist
  73832. * @param meshes list of meshes that make up the controller model to process
  73833. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  73834. */
  73835. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  73836. var loadedMeshInfo = null;
  73837. // Create a new mesh to contain the glTF hierarchy
  73838. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  73839. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  73840. var childMesh = null;
  73841. for (var i = 0; i < meshes.length; i++) {
  73842. var mesh = meshes[i];
  73843. if (!mesh.parent) {
  73844. // Exclude controller meshes from picking results
  73845. mesh.isPickable = false;
  73846. // Handle root node, attach to the new parentMesh
  73847. childMesh = mesh;
  73848. break;
  73849. }
  73850. }
  73851. if (childMesh) {
  73852. childMesh.setParent(parentMesh);
  73853. // Create our mesh info. Note that this method will always return non-null.
  73854. loadedMeshInfo = this.createMeshInfo(parentMesh);
  73855. }
  73856. else {
  73857. BABYLON.Tools.Warn('Could not find root node in model file.');
  73858. }
  73859. return loadedMeshInfo;
  73860. };
  73861. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  73862. var loadedMeshInfo = new LoadedMeshInfo();
  73863. var i;
  73864. loadedMeshInfo.rootNode = rootNode;
  73865. // Reset the caches
  73866. loadedMeshInfo.buttonMeshes = {};
  73867. loadedMeshInfo.axisMeshes = {};
  73868. // Button Meshes
  73869. for (i = 0; i < this._mapping.buttons.length; i++) {
  73870. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  73871. if (!buttonMeshName) {
  73872. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  73873. continue;
  73874. }
  73875. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  73876. if (!buttonMesh) {
  73877. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  73878. continue;
  73879. }
  73880. var buttonMeshInfo = {
  73881. index: i,
  73882. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  73883. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  73884. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  73885. };
  73886. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  73887. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  73888. }
  73889. else {
  73890. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  73891. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  73892. '(VALUE: ' + !!buttonMeshInfo.value +
  73893. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  73894. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  73895. ')');
  73896. }
  73897. }
  73898. // Axis Meshes
  73899. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  73900. var axisMeshName = this._mapping.axisMeshNames[i];
  73901. if (!axisMeshName) {
  73902. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  73903. continue;
  73904. }
  73905. var axisMesh = getChildByName(rootNode, axisMeshName);
  73906. if (!axisMesh) {
  73907. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  73908. continue;
  73909. }
  73910. var axisMeshInfo = {
  73911. index: i,
  73912. value: getImmediateChildByName(axisMesh, 'VALUE'),
  73913. min: getImmediateChildByName(axisMesh, 'MIN'),
  73914. max: getImmediateChildByName(axisMesh, 'MAX')
  73915. };
  73916. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  73917. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  73918. }
  73919. else {
  73920. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  73921. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  73922. '(VALUE: ' + !!axisMeshInfo.value +
  73923. ', MIN: ' + !!axisMeshInfo.min +
  73924. ', MAX:' + !!axisMeshInfo.max +
  73925. ')');
  73926. }
  73927. }
  73928. // Pointing Ray
  73929. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  73930. if (!loadedMeshInfo.pointingPoseNode) {
  73931. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  73932. }
  73933. else {
  73934. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  73935. }
  73936. return loadedMeshInfo;
  73937. // Look through all children recursively. This will return null if no mesh exists with the given name.
  73938. function getChildByName(node, name) {
  73939. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  73940. }
  73941. // Look through only immediate children. This will return null if no mesh exists with the given name.
  73942. function getImmediateChildByName(node, name) {
  73943. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  73944. }
  73945. };
  73946. /**
  73947. * Gets the ray of the controller in the direction the controller is pointing
  73948. * @param length the length the resulting ray should be
  73949. * @returns a ray in the direction the controller is pointing
  73950. */
  73951. WindowsMotionController.prototype.getForwardRay = function (length) {
  73952. if (length === void 0) { length = 100; }
  73953. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  73954. return _super.prototype.getForwardRay.call(this, length);
  73955. }
  73956. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  73957. var origin = m.getTranslation();
  73958. var forward = new BABYLON.Vector3(0, 0, -1);
  73959. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73960. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73961. return new BABYLON.Ray(origin, direction, length);
  73962. };
  73963. /**
  73964. * Disposes of the controller
  73965. */
  73966. WindowsMotionController.prototype.dispose = function () {
  73967. _super.prototype.dispose.call(this);
  73968. this.onTrackpadChangedObservable.clear();
  73969. };
  73970. /**
  73971. * The base url used to load the left and right controller models
  73972. */
  73973. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  73974. /**
  73975. * The name of the left controller model file
  73976. */
  73977. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  73978. /**
  73979. * The name of the right controller model file
  73980. */
  73981. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  73982. /**
  73983. * The controller name prefix for this controller type
  73984. */
  73985. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  73986. /**
  73987. * The controller id pattern for this controller type
  73988. */
  73989. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  73990. return WindowsMotionController;
  73991. }(BABYLON.WebVRController));
  73992. BABYLON.WindowsMotionController = WindowsMotionController;
  73993. })(BABYLON || (BABYLON = {}));
  73994. //# sourceMappingURL=babylon.windowsMotionController.js.map
  73995. var BABYLON;
  73996. (function (BABYLON) {
  73997. /**
  73998. * Gear VR Controller
  73999. */
  74000. var GearVRController = /** @class */ (function (_super) {
  74001. __extends(GearVRController, _super);
  74002. /**
  74003. * Creates a new GearVRController from a gamepad
  74004. * @param vrGamepad the gamepad that the controller should be created from
  74005. */
  74006. function GearVRController(vrGamepad) {
  74007. var _this = _super.call(this, vrGamepad) || this;
  74008. _this._maxRotationDistFromHeadset = Math.PI / 5;
  74009. _this._draggedRoomRotation = 0;
  74010. _this._tmpVector = new BABYLON.Vector3();
  74011. _this._buttonIndexToObservableNameMap = [
  74012. 'onTrackpadChangedObservable',
  74013. 'onTriggerStateChangedObservable' // Trigger
  74014. ];
  74015. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  74016. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  74017. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  74018. return _this;
  74019. }
  74020. /**
  74021. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74022. * @param poseData raw pose fromthe device
  74023. */
  74024. GearVRController.prototype.updateFromDevice = function (poseData) {
  74025. _super.prototype.updateFromDevice.call(this, poseData);
  74026. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  74027. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  74028. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  74029. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  74030. // Find the radian distance away that the headset is from the controllers rotation
  74031. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  74032. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  74033. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  74034. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  74035. this._draggedRoomRotation += rotationAmount;
  74036. // Rotate controller around headset
  74037. var sin = Math.sin(-rotationAmount);
  74038. var cos = Math.cos(-rotationAmount);
  74039. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  74040. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  74041. }
  74042. }
  74043. }
  74044. };
  74045. /**
  74046. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74047. * @param scene scene in which to add meshes
  74048. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74049. */
  74050. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74051. var _this = this;
  74052. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  74053. // Offset the controller so it will rotate around the users wrist
  74054. var mesh = new BABYLON.Mesh("", scene);
  74055. newMeshes[1].parent = mesh;
  74056. newMeshes[1].position.z = -0.15;
  74057. _this._defaultModel = mesh;
  74058. _this.attachToMesh(_this._defaultModel);
  74059. if (meshLoaded) {
  74060. meshLoaded(_this._defaultModel);
  74061. }
  74062. });
  74063. };
  74064. /**
  74065. * Called once for each button that changed state since the last frame
  74066. * @param buttonIdx Which button index changed
  74067. * @param state New state of the button
  74068. * @param changes Which properties on the state changed since last frame
  74069. */
  74070. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74071. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  74072. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  74073. // Only emit events for buttons that we know how to map from index to observable
  74074. var observable = this[observableName];
  74075. if (observable) {
  74076. observable.notifyObservers(state);
  74077. }
  74078. }
  74079. };
  74080. /**
  74081. * Base Url for the controller model.
  74082. */
  74083. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74084. /**
  74085. * File name for the controller model.
  74086. */
  74087. GearVRController.MODEL_FILENAME = 'generic.babylon';
  74088. /**
  74089. * Gamepad Id prefix used to identify this controller.
  74090. */
  74091. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  74092. return GearVRController;
  74093. }(BABYLON.WebVRController));
  74094. BABYLON.GearVRController = GearVRController;
  74095. })(BABYLON || (BABYLON = {}));
  74096. //# sourceMappingURL=babylon.gearVRController.js.map
  74097. var BABYLON;
  74098. (function (BABYLON) {
  74099. /**
  74100. * Google Daydream controller
  74101. */
  74102. var DaydreamController = /** @class */ (function (_super) {
  74103. __extends(DaydreamController, _super);
  74104. /**
  74105. * Creates a new DaydreamController from a gamepad
  74106. * @param vrGamepad the gamepad that the controller should be created from
  74107. */
  74108. function DaydreamController(vrGamepad) {
  74109. var _this = _super.call(this, vrGamepad) || this;
  74110. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  74111. return _this;
  74112. }
  74113. /**
  74114. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74115. * @param scene scene in which to add meshes
  74116. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74117. */
  74118. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74119. var _this = this;
  74120. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  74121. _this._defaultModel = newMeshes[1];
  74122. _this.attachToMesh(_this._defaultModel);
  74123. if (meshLoaded) {
  74124. meshLoaded(_this._defaultModel);
  74125. }
  74126. });
  74127. };
  74128. /**
  74129. * Called once for each button that changed state since the last frame
  74130. * @param buttonIdx Which button index changed
  74131. * @param state New state of the button
  74132. * @param changes Which properties on the state changed since last frame
  74133. */
  74134. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74135. // Daydream controller only has 1 GamepadButton (on the trackpad).
  74136. if (buttonIdx === 0) {
  74137. var observable = this.onTriggerStateChangedObservable;
  74138. if (observable) {
  74139. observable.notifyObservers(state);
  74140. }
  74141. }
  74142. else {
  74143. // If the app or home buttons are ever made available
  74144. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  74145. }
  74146. };
  74147. /**
  74148. * Base Url for the controller model.
  74149. */
  74150. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74151. /**
  74152. * File name for the controller model.
  74153. */
  74154. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  74155. /**
  74156. * Gamepad Id prefix used to identify Daydream Controller.
  74157. */
  74158. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  74159. return DaydreamController;
  74160. }(BABYLON.WebVRController));
  74161. BABYLON.DaydreamController = DaydreamController;
  74162. })(BABYLON || (BABYLON = {}));
  74163. //# sourceMappingURL=babylon.daydreamController.js.map
  74164. var BABYLON;
  74165. (function (BABYLON) {
  74166. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  74167. get: function () {
  74168. if (!this._gamepadManager) {
  74169. this._gamepadManager = new BABYLON.GamepadManager(this);
  74170. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  74171. if (!component) {
  74172. component = new GamepadSystemSceneComponent(this);
  74173. this._addComponent(component);
  74174. }
  74175. }
  74176. return this._gamepadManager;
  74177. },
  74178. enumerable: true,
  74179. configurable: true
  74180. });
  74181. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  74182. this.add(new BABYLON.FreeCameraGamepadInput());
  74183. return this;
  74184. };
  74185. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  74186. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  74187. return this;
  74188. };
  74189. /**
  74190. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  74191. */
  74192. var GamepadSystemSceneComponent = /** @class */ (function () {
  74193. /**
  74194. * Creates a new instance of the component for the given scene
  74195. * @param scene Defines the scene to register the component in
  74196. */
  74197. function GamepadSystemSceneComponent(scene) {
  74198. /**
  74199. * The component name helpfull to identify the component in the list of scene components.
  74200. */
  74201. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  74202. this.scene = scene;
  74203. }
  74204. /**
  74205. * Registers the component in a given scene
  74206. */
  74207. GamepadSystemSceneComponent.prototype.register = function () {
  74208. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  74209. };
  74210. /**
  74211. * Rebuilds the elements related to this component in case of
  74212. * context lost for instance.
  74213. */
  74214. GamepadSystemSceneComponent.prototype.rebuild = function () {
  74215. // Nothing to do for gamepads
  74216. };
  74217. /**
  74218. * Disposes the component and the associated ressources
  74219. */
  74220. GamepadSystemSceneComponent.prototype.dispose = function () {
  74221. var gamepadManager = this.scene._gamepadManager;
  74222. if (gamepadManager) {
  74223. gamepadManager.dispose();
  74224. this.scene._gamepadManager = null;
  74225. }
  74226. };
  74227. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  74228. var gamepadManager = this.scene._gamepadManager;
  74229. if (gamepadManager && gamepadManager._isMonitoring) {
  74230. gamepadManager._checkGamepadsStatus();
  74231. }
  74232. };
  74233. return GamepadSystemSceneComponent;
  74234. }());
  74235. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  74236. })(BABYLON || (BABYLON = {}));
  74237. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  74238. var BABYLON;
  74239. (function (BABYLON) {
  74240. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  74241. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  74242. });
  74243. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  74244. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  74245. });
  74246. var FollowCamera = /** @class */ (function (_super) {
  74247. __extends(FollowCamera, _super);
  74248. function FollowCamera(name, position, scene, lockedTarget) {
  74249. if (lockedTarget === void 0) { lockedTarget = null; }
  74250. var _this = _super.call(this, name, position, scene) || this;
  74251. _this.radius = 12;
  74252. _this.rotationOffset = 0;
  74253. _this.heightOffset = 4;
  74254. _this.cameraAcceleration = 0.05;
  74255. _this.maxCameraSpeed = 20;
  74256. _this.lockedTarget = lockedTarget;
  74257. return _this;
  74258. }
  74259. FollowCamera.prototype.getRadians = function (degrees) {
  74260. return degrees * Math.PI / 180;
  74261. };
  74262. FollowCamera.prototype.follow = function (cameraTarget) {
  74263. if (!cameraTarget)
  74264. return;
  74265. var yRotation;
  74266. if (cameraTarget.rotationQuaternion) {
  74267. var rotMatrix = new BABYLON.Matrix();
  74268. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  74269. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  74270. }
  74271. else {
  74272. yRotation = cameraTarget.rotation.y;
  74273. }
  74274. var radians = this.getRadians(this.rotationOffset) + yRotation;
  74275. var targetPosition = cameraTarget.getAbsolutePosition();
  74276. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  74277. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  74278. var dx = targetX - this.position.x;
  74279. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  74280. var dz = (targetZ) - this.position.z;
  74281. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  74282. var vy = dy * this.cameraAcceleration;
  74283. var vz = dz * this.cameraAcceleration * 2;
  74284. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  74285. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74286. }
  74287. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  74288. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74289. }
  74290. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  74291. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74292. }
  74293. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  74294. this.setTarget(targetPosition);
  74295. };
  74296. FollowCamera.prototype._checkInputs = function () {
  74297. _super.prototype._checkInputs.call(this);
  74298. if (this.lockedTarget) {
  74299. this.follow(this.lockedTarget);
  74300. }
  74301. };
  74302. FollowCamera.prototype.getClassName = function () {
  74303. return "FollowCamera";
  74304. };
  74305. __decorate([
  74306. BABYLON.serialize()
  74307. ], FollowCamera.prototype, "radius", void 0);
  74308. __decorate([
  74309. BABYLON.serialize()
  74310. ], FollowCamera.prototype, "rotationOffset", void 0);
  74311. __decorate([
  74312. BABYLON.serialize()
  74313. ], FollowCamera.prototype, "heightOffset", void 0);
  74314. __decorate([
  74315. BABYLON.serialize()
  74316. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  74317. __decorate([
  74318. BABYLON.serialize()
  74319. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  74320. __decorate([
  74321. BABYLON.serializeAsMeshReference("lockedTargetId")
  74322. ], FollowCamera.prototype, "lockedTarget", void 0);
  74323. return FollowCamera;
  74324. }(BABYLON.TargetCamera));
  74325. BABYLON.FollowCamera = FollowCamera;
  74326. var ArcFollowCamera = /** @class */ (function (_super) {
  74327. __extends(ArcFollowCamera, _super);
  74328. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  74329. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  74330. _this.alpha = alpha;
  74331. _this.beta = beta;
  74332. _this.radius = radius;
  74333. _this.target = target;
  74334. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  74335. _this.follow();
  74336. return _this;
  74337. }
  74338. ArcFollowCamera.prototype.follow = function () {
  74339. if (!this.target) {
  74340. return;
  74341. }
  74342. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  74343. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  74344. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  74345. var targetPosition = this.target.getAbsolutePosition();
  74346. this.position = targetPosition.add(this._cartesianCoordinates);
  74347. this.setTarget(targetPosition);
  74348. };
  74349. ArcFollowCamera.prototype._checkInputs = function () {
  74350. _super.prototype._checkInputs.call(this);
  74351. this.follow();
  74352. };
  74353. ArcFollowCamera.prototype.getClassName = function () {
  74354. return "ArcFollowCamera";
  74355. };
  74356. return ArcFollowCamera;
  74357. }(BABYLON.TargetCamera));
  74358. BABYLON.ArcFollowCamera = ArcFollowCamera;
  74359. })(BABYLON || (BABYLON = {}));
  74360. //# sourceMappingURL=babylon.followCamera.js.map
  74361. var BABYLON;
  74362. (function (BABYLON) {
  74363. // We're mainly based on the logic defined into the FreeCamera code
  74364. var UniversalCamera = /** @class */ (function (_super) {
  74365. __extends(UniversalCamera, _super);
  74366. //-- end properties for backward compatibility for inputs
  74367. function UniversalCamera(name, position, scene) {
  74368. var _this = _super.call(this, name, position, scene) || this;
  74369. _this.inputs.addGamepad();
  74370. return _this;
  74371. }
  74372. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  74373. //-- Begin properties for backward compatibility for inputs
  74374. get: function () {
  74375. var gamepad = this.inputs.attached["gamepad"];
  74376. if (gamepad)
  74377. return gamepad.gamepadAngularSensibility;
  74378. return 0;
  74379. },
  74380. set: function (value) {
  74381. var gamepad = this.inputs.attached["gamepad"];
  74382. if (gamepad)
  74383. gamepad.gamepadAngularSensibility = value;
  74384. },
  74385. enumerable: true,
  74386. configurable: true
  74387. });
  74388. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  74389. get: function () {
  74390. var gamepad = this.inputs.attached["gamepad"];
  74391. if (gamepad)
  74392. return gamepad.gamepadMoveSensibility;
  74393. return 0;
  74394. },
  74395. set: function (value) {
  74396. var gamepad = this.inputs.attached["gamepad"];
  74397. if (gamepad)
  74398. gamepad.gamepadMoveSensibility = value;
  74399. },
  74400. enumerable: true,
  74401. configurable: true
  74402. });
  74403. UniversalCamera.prototype.getClassName = function () {
  74404. return "UniversalCamera";
  74405. };
  74406. return UniversalCamera;
  74407. }(BABYLON.TouchCamera));
  74408. BABYLON.UniversalCamera = UniversalCamera;
  74409. })(BABYLON || (BABYLON = {}));
  74410. //# sourceMappingURL=babylon.universalCamera.js.map
  74411. var BABYLON;
  74412. (function (BABYLON) {
  74413. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  74414. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  74415. });
  74416. // We're mainly based on the logic defined into the FreeCamera code
  74417. var GamepadCamera = /** @class */ (function (_super) {
  74418. __extends(GamepadCamera, _super);
  74419. //-- end properties for backward compatibility for inputs
  74420. function GamepadCamera(name, position, scene) {
  74421. return _super.call(this, name, position, scene) || this;
  74422. }
  74423. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  74424. //-- Begin properties for backward compatibility for inputs
  74425. get: function () {
  74426. var gamepad = this.inputs.attached["gamepad"];
  74427. if (gamepad)
  74428. return gamepad.gamepadAngularSensibility;
  74429. return 0;
  74430. },
  74431. set: function (value) {
  74432. var gamepad = this.inputs.attached["gamepad"];
  74433. if (gamepad)
  74434. gamepad.gamepadAngularSensibility = value;
  74435. },
  74436. enumerable: true,
  74437. configurable: true
  74438. });
  74439. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  74440. get: function () {
  74441. var gamepad = this.inputs.attached["gamepad"];
  74442. if (gamepad)
  74443. return gamepad.gamepadMoveSensibility;
  74444. return 0;
  74445. },
  74446. set: function (value) {
  74447. var gamepad = this.inputs.attached["gamepad"];
  74448. if (gamepad)
  74449. gamepad.gamepadMoveSensibility = value;
  74450. },
  74451. enumerable: true,
  74452. configurable: true
  74453. });
  74454. GamepadCamera.prototype.getClassName = function () {
  74455. return "GamepadCamera";
  74456. };
  74457. return GamepadCamera;
  74458. }(BABYLON.UniversalCamera));
  74459. BABYLON.GamepadCamera = GamepadCamera;
  74460. })(BABYLON || (BABYLON = {}));
  74461. //# sourceMappingURL=babylon.gamepadCamera.js.map
  74462. var BABYLON;
  74463. (function (BABYLON) {
  74464. var PostProcessRenderPipelineManager = /** @class */ (function () {
  74465. function PostProcessRenderPipelineManager() {
  74466. this._renderPipelines = {};
  74467. }
  74468. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  74469. this._renderPipelines[renderPipeline._name] = renderPipeline;
  74470. };
  74471. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  74472. if (unique === void 0) { unique = false; }
  74473. var renderPipeline = this._renderPipelines[renderPipelineName];
  74474. if (!renderPipeline) {
  74475. return;
  74476. }
  74477. renderPipeline._attachCameras(cameras, unique);
  74478. };
  74479. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  74480. var renderPipeline = this._renderPipelines[renderPipelineName];
  74481. if (!renderPipeline) {
  74482. return;
  74483. }
  74484. renderPipeline._detachCameras(cameras);
  74485. };
  74486. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74487. var renderPipeline = this._renderPipelines[renderPipelineName];
  74488. if (!renderPipeline) {
  74489. return;
  74490. }
  74491. renderPipeline._enableEffect(renderEffectName, cameras);
  74492. };
  74493. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74494. var renderPipeline = this._renderPipelines[renderPipelineName];
  74495. if (!renderPipeline) {
  74496. return;
  74497. }
  74498. renderPipeline._disableEffect(renderEffectName, cameras);
  74499. };
  74500. PostProcessRenderPipelineManager.prototype.update = function () {
  74501. for (var renderPipelineName in this._renderPipelines) {
  74502. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74503. var pipeline = this._renderPipelines[renderPipelineName];
  74504. if (!pipeline.isSupported) {
  74505. pipeline.dispose();
  74506. delete this._renderPipelines[renderPipelineName];
  74507. }
  74508. else {
  74509. pipeline._update();
  74510. }
  74511. }
  74512. }
  74513. };
  74514. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  74515. for (var renderPipelineName in this._renderPipelines) {
  74516. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74517. var pipeline = this._renderPipelines[renderPipelineName];
  74518. pipeline._rebuild();
  74519. }
  74520. }
  74521. };
  74522. PostProcessRenderPipelineManager.prototype.dispose = function () {
  74523. for (var renderPipelineName in this._renderPipelines) {
  74524. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74525. var pipeline = this._renderPipelines[renderPipelineName];
  74526. pipeline.dispose();
  74527. }
  74528. }
  74529. };
  74530. return PostProcessRenderPipelineManager;
  74531. }());
  74532. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  74533. })(BABYLON || (BABYLON = {}));
  74534. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  74535. var BABYLON;
  74536. (function (BABYLON) {
  74537. /**
  74538. * This represents a set of one or more post processes in Babylon.
  74539. * A post process can be used to apply a shader to a texture after it is rendered.
  74540. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  74541. */
  74542. var PostProcessRenderEffect = /** @class */ (function () {
  74543. /**
  74544. * Instantiates a post process render effect.
  74545. * A post process can be used to apply a shader to a texture after it is rendered.
  74546. * @param engine The engine the effect is tied to
  74547. * @param name The name of the effect
  74548. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  74549. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  74550. */
  74551. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  74552. this._name = name;
  74553. this._singleInstance = singleInstance || true;
  74554. this._getPostProcesses = getPostProcesses;
  74555. this._cameras = {};
  74556. this._indicesForCamera = {};
  74557. this._postProcesses = {};
  74558. }
  74559. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  74560. /**
  74561. * Checks if all the post processes in the effect are supported.
  74562. */
  74563. get: function () {
  74564. for (var index in this._postProcesses) {
  74565. if (this._postProcesses.hasOwnProperty(index)) {
  74566. var pps = this._postProcesses[index];
  74567. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  74568. if (!pps[ppIndex].isSupported) {
  74569. return false;
  74570. }
  74571. }
  74572. }
  74573. }
  74574. return true;
  74575. },
  74576. enumerable: true,
  74577. configurable: true
  74578. });
  74579. /**
  74580. * Updates the current state of the effect
  74581. */
  74582. PostProcessRenderEffect.prototype._update = function () {
  74583. };
  74584. /**
  74585. * Attaches the effect on cameras
  74586. * @param cameras The camera to attach to.
  74587. */
  74588. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  74589. var _this = this;
  74590. var cameraKey;
  74591. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74592. if (!cams) {
  74593. return;
  74594. }
  74595. for (var i = 0; i < cams.length; i++) {
  74596. var camera = cams[i];
  74597. var cameraName = camera.name;
  74598. if (this._singleInstance) {
  74599. cameraKey = 0;
  74600. }
  74601. else {
  74602. cameraKey = cameraName;
  74603. }
  74604. if (!this._postProcesses[cameraKey]) {
  74605. var postProcess = this._getPostProcesses();
  74606. if (postProcess) {
  74607. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  74608. }
  74609. }
  74610. if (!this._indicesForCamera[cameraName]) {
  74611. this._indicesForCamera[cameraName] = [];
  74612. }
  74613. this._postProcesses[cameraKey].forEach(function (postProcess) {
  74614. var index = camera.attachPostProcess(postProcess);
  74615. _this._indicesForCamera[cameraName].push(index);
  74616. });
  74617. if (!this._cameras[cameraName]) {
  74618. this._cameras[cameraName] = camera;
  74619. }
  74620. }
  74621. };
  74622. /**
  74623. * Detatches the effect on cameras
  74624. * @param cameras The camera to detatch from.
  74625. */
  74626. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  74627. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74628. if (!cams) {
  74629. return;
  74630. }
  74631. for (var i = 0; i < cams.length; i++) {
  74632. var camera = cams[i];
  74633. var cameraName = camera.name;
  74634. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74635. camera.detachPostProcess(postProcess);
  74636. });
  74637. if (this._cameras[cameraName]) {
  74638. //this._indicesForCamera.splice(index, 1);
  74639. this._cameras[cameraName] = null;
  74640. }
  74641. }
  74642. };
  74643. /**
  74644. * Enables the effect on given cameras
  74645. * @param cameras The camera to enable.
  74646. */
  74647. PostProcessRenderEffect.prototype._enable = function (cameras) {
  74648. var _this = this;
  74649. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74650. if (!cams) {
  74651. return;
  74652. }
  74653. for (var i = 0; i < cams.length; i++) {
  74654. var camera = cams[i];
  74655. var cameraName = camera.name;
  74656. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  74657. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  74658. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74659. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  74660. });
  74661. }
  74662. }
  74663. }
  74664. };
  74665. /**
  74666. * Disables the effect on the given cameras
  74667. * @param cameras The camera to disable.
  74668. */
  74669. PostProcessRenderEffect.prototype._disable = function (cameras) {
  74670. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74671. if (!cams) {
  74672. return;
  74673. }
  74674. for (var i = 0; i < cams.length; i++) {
  74675. var camera = cams[i];
  74676. var cameraName = camera.name;
  74677. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74678. camera.detachPostProcess(postProcess);
  74679. });
  74680. }
  74681. };
  74682. /**
  74683. * Gets a list of the post processes contained in the effect.
  74684. * @param camera The camera to get the post processes on.
  74685. * @returns The list of the post processes in the effect.
  74686. */
  74687. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  74688. if (this._singleInstance) {
  74689. return this._postProcesses[0];
  74690. }
  74691. else {
  74692. if (!camera) {
  74693. return null;
  74694. }
  74695. return this._postProcesses[camera.name];
  74696. }
  74697. };
  74698. return PostProcessRenderEffect;
  74699. }());
  74700. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  74701. })(BABYLON || (BABYLON = {}));
  74702. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  74703. var BABYLON;
  74704. (function (BABYLON) {
  74705. var PostProcessRenderPipeline = /** @class */ (function () {
  74706. function PostProcessRenderPipeline(engine, name) {
  74707. this.engine = engine;
  74708. this._name = name;
  74709. this._renderEffects = {};
  74710. this._renderEffectsForIsolatedPass = new Array();
  74711. this._cameras = [];
  74712. }
  74713. PostProcessRenderPipeline.prototype.getClassName = function () {
  74714. return "PostProcessRenderPipeline";
  74715. };
  74716. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  74717. get: function () {
  74718. for (var renderEffectName in this._renderEffects) {
  74719. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74720. if (!this._renderEffects[renderEffectName].isSupported) {
  74721. return false;
  74722. }
  74723. }
  74724. }
  74725. return true;
  74726. },
  74727. enumerable: true,
  74728. configurable: true
  74729. });
  74730. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  74731. this._renderEffects[renderEffect._name] = renderEffect;
  74732. };
  74733. // private
  74734. PostProcessRenderPipeline.prototype._rebuild = function () {
  74735. };
  74736. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  74737. var renderEffects = this._renderEffects[renderEffectName];
  74738. if (!renderEffects) {
  74739. return;
  74740. }
  74741. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74742. };
  74743. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  74744. var renderEffects = this._renderEffects[renderEffectName];
  74745. if (!renderEffects) {
  74746. return;
  74747. }
  74748. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74749. };
  74750. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  74751. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74752. if (!cams) {
  74753. return;
  74754. }
  74755. var indicesToDelete = [];
  74756. var i;
  74757. for (i = 0; i < cams.length; i++) {
  74758. var camera = cams[i];
  74759. var cameraName = camera.name;
  74760. if (this._cameras.indexOf(camera) === -1) {
  74761. this._cameras[cameraName] = camera;
  74762. }
  74763. else if (unique) {
  74764. indicesToDelete.push(i);
  74765. }
  74766. }
  74767. for (i = 0; i < indicesToDelete.length; i++) {
  74768. cameras.splice(indicesToDelete[i], 1);
  74769. }
  74770. for (var renderEffectName in this._renderEffects) {
  74771. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74772. this._renderEffects[renderEffectName]._attachCameras(cams);
  74773. }
  74774. }
  74775. };
  74776. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  74777. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74778. if (!cams) {
  74779. return;
  74780. }
  74781. for (var renderEffectName in this._renderEffects) {
  74782. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74783. this._renderEffects[renderEffectName]._detachCameras(cams);
  74784. }
  74785. }
  74786. for (var i = 0; i < cams.length; i++) {
  74787. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  74788. }
  74789. };
  74790. PostProcessRenderPipeline.prototype._update = function () {
  74791. for (var renderEffectName in this._renderEffects) {
  74792. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74793. this._renderEffects[renderEffectName]._update();
  74794. }
  74795. }
  74796. for (var i = 0; i < this._cameras.length; i++) {
  74797. var cameraName = this._cameras[i].name;
  74798. if (this._renderEffectsForIsolatedPass[cameraName]) {
  74799. this._renderEffectsForIsolatedPass[cameraName]._update();
  74800. }
  74801. }
  74802. };
  74803. PostProcessRenderPipeline.prototype._reset = function () {
  74804. this._renderEffects = {};
  74805. this._renderEffectsForIsolatedPass = new Array();
  74806. };
  74807. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  74808. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  74809. var effectKeys = Object.keys(this._renderEffects);
  74810. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  74811. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  74812. if (postProcesses) {
  74813. postProcesses[0].samples = sampleCount;
  74814. return true;
  74815. }
  74816. }
  74817. return false;
  74818. };
  74819. PostProcessRenderPipeline.prototype.dispose = function () {
  74820. // Must be implemented by children
  74821. };
  74822. __decorate([
  74823. BABYLON.serialize()
  74824. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  74825. return PostProcessRenderPipeline;
  74826. }());
  74827. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  74828. })(BABYLON || (BABYLON = {}));
  74829. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  74830. var BABYLON;
  74831. (function (BABYLON) {
  74832. /**
  74833. * This represents a depth renderer in Babylon.
  74834. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  74835. */
  74836. var DepthRenderer = /** @class */ (function () {
  74837. /**
  74838. * Instantiates a depth renderer
  74839. * @param scene The scene the renderer belongs to
  74840. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  74841. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  74842. */
  74843. function DepthRenderer(scene, type, camera) {
  74844. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74845. if (camera === void 0) { camera = null; }
  74846. var _this = this;
  74847. this._scene = scene;
  74848. this._camera = camera;
  74849. var engine = scene.getEngine();
  74850. // Render target
  74851. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  74852. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74853. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74854. this._depthMap.refreshRate = 1;
  74855. this._depthMap.renderParticles = false;
  74856. this._depthMap.renderList = null;
  74857. // Camera to get depth map from to support multiple concurrent cameras
  74858. this._depthMap.activeCamera = this._camera;
  74859. this._depthMap.ignoreCameraViewport = true;
  74860. this._depthMap.useCameraPostProcesses = false;
  74861. // set default depth value to 1.0 (far away)
  74862. this._depthMap.onClearObservable.add(function (engine) {
  74863. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  74864. });
  74865. // Custom render function
  74866. var renderSubMesh = function (subMesh) {
  74867. var mesh = subMesh.getRenderingMesh();
  74868. var scene = _this._scene;
  74869. var engine = scene.getEngine();
  74870. var material = subMesh.getMaterial();
  74871. if (!material) {
  74872. return;
  74873. }
  74874. // Culling and reverse (right handed system)
  74875. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74876. // Managing instances
  74877. var batch = mesh._getInstancesRenderList(subMesh._id);
  74878. if (batch.mustReturn) {
  74879. return;
  74880. }
  74881. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74882. var camera = _this._camera || scene.activeCamera;
  74883. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  74884. engine.enableEffect(_this._effect);
  74885. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74886. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74887. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  74888. // Alpha test
  74889. if (material && material.needAlphaTesting()) {
  74890. var alphaTexture = material.getAlphaTestTexture();
  74891. if (alphaTexture) {
  74892. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74893. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74894. }
  74895. }
  74896. // Bones
  74897. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74898. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74899. }
  74900. // Draw
  74901. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74902. }
  74903. };
  74904. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74905. var index;
  74906. if (depthOnlySubMeshes.length) {
  74907. engine.setColorWrite(false);
  74908. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74909. renderSubMesh(depthOnlySubMeshes.data[index]);
  74910. }
  74911. engine.setColorWrite(true);
  74912. }
  74913. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74914. renderSubMesh(opaqueSubMeshes.data[index]);
  74915. }
  74916. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74917. renderSubMesh(alphaTestSubMeshes.data[index]);
  74918. }
  74919. };
  74920. }
  74921. /**
  74922. * Creates the depth rendering effect and checks if the effect is ready.
  74923. * @param subMesh The submesh to be used to render the depth map of
  74924. * @param useInstances If multiple world instances should be used
  74925. * @returns if the depth renderer is ready to render the depth map
  74926. */
  74927. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  74928. var material = subMesh.getMaterial();
  74929. if (material.disableDepthWrite) {
  74930. return false;
  74931. }
  74932. var defines = [];
  74933. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74934. var mesh = subMesh.getMesh();
  74935. // Alpha test
  74936. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  74937. defines.push("#define ALPHATEST");
  74938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74939. attribs.push(BABYLON.VertexBuffer.UVKind);
  74940. defines.push("#define UV1");
  74941. }
  74942. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74943. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74944. defines.push("#define UV2");
  74945. }
  74946. }
  74947. // Bones
  74948. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74949. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74950. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74951. if (mesh.numBoneInfluencers > 4) {
  74952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74954. }
  74955. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74956. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74957. }
  74958. else {
  74959. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74960. }
  74961. // Instances
  74962. if (useInstances) {
  74963. defines.push("#define INSTANCES");
  74964. attribs.push("world0");
  74965. attribs.push("world1");
  74966. attribs.push("world2");
  74967. attribs.push("world3");
  74968. }
  74969. // Get correct effect
  74970. var join = defines.join("\n");
  74971. if (this._cachedDefines !== join) {
  74972. this._cachedDefines = join;
  74973. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  74974. }
  74975. return this._effect.isReady();
  74976. };
  74977. /**
  74978. * Gets the texture which the depth map will be written to.
  74979. * @returns The depth map texture
  74980. */
  74981. DepthRenderer.prototype.getDepthMap = function () {
  74982. return this._depthMap;
  74983. };
  74984. /**
  74985. * Disposes of the depth renderer.
  74986. */
  74987. DepthRenderer.prototype.dispose = function () {
  74988. this._depthMap.dispose();
  74989. };
  74990. return DepthRenderer;
  74991. }());
  74992. BABYLON.DepthRenderer = DepthRenderer;
  74993. })(BABYLON || (BABYLON = {}));
  74994. //# sourceMappingURL=babylon.depthRenderer.js.map
  74995. var BABYLON;
  74996. (function (BABYLON) {
  74997. var SSAORenderingPipeline = /** @class */ (function (_super) {
  74998. __extends(SSAORenderingPipeline, _super);
  74999. /**
  75000. * @constructor
  75001. * @param {string} name - The rendering pipeline name
  75002. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75003. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  75004. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75005. */
  75006. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  75007. var _this = _super.call(this, scene.getEngine(), name) || this;
  75008. // Members
  75009. /**
  75010. * The PassPostProcess id in the pipeline that contains the original scene color
  75011. */
  75012. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75013. /**
  75014. * The SSAO PostProcess id in the pipeline
  75015. */
  75016. _this.SSAORenderEffect = "SSAORenderEffect";
  75017. /**
  75018. * The horizontal blur PostProcess id in the pipeline
  75019. */
  75020. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75021. /**
  75022. * The vertical blur PostProcess id in the pipeline
  75023. */
  75024. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75025. /**
  75026. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75027. */
  75028. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75029. /**
  75030. * The output strength of the SSAO post-process. Default value is 1.0.
  75031. */
  75032. _this.totalStrength = 1.0;
  75033. /**
  75034. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  75035. */
  75036. _this.radius = 0.0001;
  75037. /**
  75038. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  75039. * Must not be equal to fallOff and superior to fallOff.
  75040. * Default value is 0.975
  75041. */
  75042. _this.area = 0.0075;
  75043. /**
  75044. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  75045. * Must not be equal to area and inferior to area.
  75046. * Default value is 0.0
  75047. */
  75048. _this.fallOff = 0.000001;
  75049. /**
  75050. * The base color of the SSAO post-process
  75051. * The final result is "base + ssao" between [0, 1]
  75052. */
  75053. _this.base = 0.5;
  75054. _this._firstUpdate = true;
  75055. _this._scene = scene;
  75056. // Set up assets
  75057. _this._createRandomTexture();
  75058. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75059. var ssaoRatio = ratio.ssaoRatio || ratio;
  75060. var combineRatio = ratio.combineRatio || ratio;
  75061. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75062. _this._createSSAOPostProcess(ssaoRatio);
  75063. _this._createBlurPostProcess(ssaoRatio);
  75064. _this._createSSAOCombinePostProcess(combineRatio);
  75065. // Set up pipeline
  75066. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75067. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75068. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75069. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75070. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75071. // Finish
  75072. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75073. if (cameras)
  75074. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75075. return _this;
  75076. }
  75077. // Public Methods
  75078. /**
  75079. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75080. */
  75081. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75082. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75083. for (var i = 0; i < this._scene.cameras.length; i++) {
  75084. var camera = this._scene.cameras[i];
  75085. this._originalColorPostProcess.dispose(camera);
  75086. this._ssaoPostProcess.dispose(camera);
  75087. this._blurHPostProcess.dispose(camera);
  75088. this._blurVPostProcess.dispose(camera);
  75089. this._ssaoCombinePostProcess.dispose(camera);
  75090. }
  75091. this._randomTexture.dispose();
  75092. if (disableDepthRender)
  75093. this._scene.disableDepthRenderer();
  75094. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75095. _super.prototype.dispose.call(this);
  75096. };
  75097. // Private Methods
  75098. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  75099. var _this = this;
  75100. var size = 16;
  75101. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75102. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75103. this._blurHPostProcess.onActivateObservable.add(function () {
  75104. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  75105. _this._blurHPostProcess.kernel = size * dw;
  75106. });
  75107. this._blurVPostProcess.onActivateObservable.add(function () {
  75108. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  75109. _this._blurVPostProcess.kernel = size * dw;
  75110. });
  75111. };
  75112. SSAORenderingPipeline.prototype._rebuild = function () {
  75113. this._firstUpdate = true;
  75114. _super.prototype._rebuild.call(this);
  75115. };
  75116. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75117. var _this = this;
  75118. var numSamples = 16;
  75119. var sampleSphere = [
  75120. 0.5381, 0.1856, -0.4319,
  75121. 0.1379, 0.2486, 0.4430,
  75122. 0.3371, 0.5679, -0.0057,
  75123. -0.6999, -0.0451, -0.0019,
  75124. 0.0689, -0.1598, -0.8547,
  75125. 0.0560, 0.0069, -0.1843,
  75126. -0.0146, 0.1402, 0.0762,
  75127. 0.0100, -0.1924, -0.0344,
  75128. -0.3577, -0.5301, -0.4358,
  75129. -0.3169, 0.1063, 0.0158,
  75130. 0.0103, -0.5869, 0.0046,
  75131. -0.0897, -0.4940, 0.3287,
  75132. 0.7119, -0.0154, -0.0918,
  75133. -0.0533, 0.0596, -0.5411,
  75134. 0.0352, -0.0631, 0.5460,
  75135. -0.4776, 0.2847, -0.0271
  75136. ];
  75137. var samplesFactor = 1.0 / numSamples;
  75138. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  75139. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75140. "area", "fallOff", "base", "range", "viewport"
  75141. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75142. this._ssaoPostProcess.onApply = function (effect) {
  75143. if (_this._firstUpdate) {
  75144. effect.setArray3("sampleSphere", sampleSphere);
  75145. effect.setFloat("samplesFactor", samplesFactor);
  75146. effect.setFloat("randTextureTiles", 4.0);
  75147. }
  75148. effect.setFloat("totalStrength", _this.totalStrength);
  75149. effect.setFloat("radius", _this.radius);
  75150. effect.setFloat("area", _this.area);
  75151. effect.setFloat("fallOff", _this.fallOff);
  75152. effect.setFloat("base", _this.base);
  75153. effect.setTexture("textureSampler", _this._depthTexture);
  75154. effect.setTexture("randomSampler", _this._randomTexture);
  75155. };
  75156. };
  75157. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75158. var _this = this;
  75159. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75160. this._ssaoCombinePostProcess.onApply = function (effect) {
  75161. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  75162. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75163. };
  75164. };
  75165. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  75166. var size = 512;
  75167. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75168. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75169. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75170. var context = this._randomTexture.getContext();
  75171. var rand = function (min, max) {
  75172. return Math.random() * (max - min) + min;
  75173. };
  75174. var randVector = BABYLON.Vector3.Zero();
  75175. for (var x = 0; x < size; x++) {
  75176. for (var y = 0; y < size; y++) {
  75177. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  75178. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  75179. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  75180. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75181. context.fillRect(x, y, 1, 1);
  75182. }
  75183. }
  75184. this._randomTexture.update(false);
  75185. };
  75186. __decorate([
  75187. BABYLON.serialize()
  75188. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  75189. __decorate([
  75190. BABYLON.serialize()
  75191. ], SSAORenderingPipeline.prototype, "radius", void 0);
  75192. __decorate([
  75193. BABYLON.serialize()
  75194. ], SSAORenderingPipeline.prototype, "area", void 0);
  75195. __decorate([
  75196. BABYLON.serialize()
  75197. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  75198. __decorate([
  75199. BABYLON.serialize()
  75200. ], SSAORenderingPipeline.prototype, "base", void 0);
  75201. return SSAORenderingPipeline;
  75202. }(BABYLON.PostProcessRenderPipeline));
  75203. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  75204. })(BABYLON || (BABYLON = {}));
  75205. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  75206. var BABYLON;
  75207. (function (BABYLON) {
  75208. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  75209. __extends(SSAO2RenderingPipeline, _super);
  75210. /**
  75211. * @constructor
  75212. * @param {string} name - The rendering pipeline name
  75213. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75214. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  75215. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75216. */
  75217. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  75218. var _this = _super.call(this, scene.getEngine(), name) || this;
  75219. // Members
  75220. /**
  75221. * The PassPostProcess id in the pipeline that contains the original scene color
  75222. */
  75223. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75224. /**
  75225. * The SSAO PostProcess id in the pipeline
  75226. */
  75227. _this.SSAORenderEffect = "SSAORenderEffect";
  75228. /**
  75229. * The horizontal blur PostProcess id in the pipeline
  75230. */
  75231. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75232. /**
  75233. * The vertical blur PostProcess id in the pipeline
  75234. */
  75235. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75236. /**
  75237. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75238. */
  75239. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75240. /**
  75241. * The output strength of the SSAO post-process. Default value is 1.0.
  75242. */
  75243. _this.totalStrength = 1.0;
  75244. /**
  75245. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  75246. */
  75247. _this.maxZ = 100.0;
  75248. /**
  75249. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  75250. */
  75251. _this.minZAspect = 0.2;
  75252. /**
  75253. * Number of samples used for the SSAO calculations. Default value is 8
  75254. */
  75255. _this._samples = 8;
  75256. /**
  75257. * Are we using bilateral blur ?
  75258. */
  75259. _this._expensiveBlur = true;
  75260. /**
  75261. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  75262. */
  75263. _this.radius = 2.0;
  75264. /**
  75265. * The base color of the SSAO post-process
  75266. * The final result is "base + ssao" between [0, 1]
  75267. */
  75268. _this.base = 0.1;
  75269. _this._firstUpdate = true;
  75270. _this._scene = scene;
  75271. _this._ratio = ratio;
  75272. if (!_this.isSupported) {
  75273. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  75274. return _this;
  75275. }
  75276. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  75277. var blurRatio = _this._ratio.blurRatio || ratio;
  75278. // Set up assets
  75279. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  75280. _this._createRandomTexture();
  75281. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  75282. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  75283. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75284. _this._createSSAOPostProcess(1.0);
  75285. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  75286. _this._createSSAOCombinePostProcess(blurRatio);
  75287. // Set up pipeline
  75288. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75289. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75290. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75291. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75292. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75293. // Finish
  75294. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75295. if (cameras)
  75296. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75297. return _this;
  75298. }
  75299. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  75300. get: function () {
  75301. return this._samples;
  75302. },
  75303. set: function (n) {
  75304. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  75305. this._samples = n;
  75306. this._sampleSphere = this._generateHemisphere();
  75307. this._firstUpdate = true;
  75308. },
  75309. enumerable: true,
  75310. configurable: true
  75311. });
  75312. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  75313. get: function () {
  75314. return this._expensiveBlur;
  75315. },
  75316. set: function (b) {
  75317. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  75318. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  75319. this._expensiveBlur = b;
  75320. this._firstUpdate = true;
  75321. },
  75322. enumerable: true,
  75323. configurable: true
  75324. });
  75325. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  75326. /**
  75327. * Support test.
  75328. */
  75329. get: function () {
  75330. var engine = BABYLON.Engine.LastCreatedEngine;
  75331. if (!engine) {
  75332. return false;
  75333. }
  75334. return engine.getCaps().drawBuffersExtension;
  75335. },
  75336. enumerable: true,
  75337. configurable: true
  75338. });
  75339. // Public Methods
  75340. /**
  75341. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75342. */
  75343. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  75344. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  75345. for (var i = 0; i < this._scene.cameras.length; i++) {
  75346. var camera = this._scene.cameras[i];
  75347. this._originalColorPostProcess.dispose(camera);
  75348. this._ssaoPostProcess.dispose(camera);
  75349. this._blurHPostProcess.dispose(camera);
  75350. this._blurVPostProcess.dispose(camera);
  75351. this._ssaoCombinePostProcess.dispose(camera);
  75352. }
  75353. this._randomTexture.dispose();
  75354. if (disableGeometryBufferRenderer)
  75355. this._scene.disableGeometryBufferRenderer();
  75356. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75357. _super.prototype.dispose.call(this);
  75358. };
  75359. // Private Methods
  75360. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  75361. var _this = this;
  75362. this._samplerOffsets = [];
  75363. var expensive = this.expensiveBlur;
  75364. for (var i = -8; i < 8; i++) {
  75365. this._samplerOffsets.push(i * 2 + 0.5);
  75366. }
  75367. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  75368. this._blurHPostProcess.onApply = function (effect) {
  75369. if (!_this._scene.activeCamera) {
  75370. return;
  75371. }
  75372. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  75373. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75374. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75375. effect.setFloat("radius", _this.radius);
  75376. effect.setTexture("depthSampler", _this._depthTexture);
  75377. if (_this._firstUpdate) {
  75378. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75379. }
  75380. };
  75381. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  75382. this._blurVPostProcess.onApply = function (effect) {
  75383. if (!_this._scene.activeCamera) {
  75384. return;
  75385. }
  75386. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  75387. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75388. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75389. effect.setFloat("radius", _this.radius);
  75390. effect.setTexture("depthSampler", _this._depthTexture);
  75391. if (_this._firstUpdate) {
  75392. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75393. _this._firstUpdate = false;
  75394. }
  75395. };
  75396. };
  75397. SSAO2RenderingPipeline.prototype._rebuild = function () {
  75398. this._firstUpdate = true;
  75399. _super.prototype._rebuild.call(this);
  75400. };
  75401. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  75402. var numSamples = this.samples;
  75403. var result = [];
  75404. var vector, scale;
  75405. var rand = function (min, max) {
  75406. return Math.random() * (max - min) + min;
  75407. };
  75408. var i = 0;
  75409. while (i < numSamples) {
  75410. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  75411. vector.normalize();
  75412. scale = i / numSamples;
  75413. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  75414. vector.scaleInPlace(scale);
  75415. result.push(vector.x, vector.y, vector.z);
  75416. i++;
  75417. }
  75418. return result;
  75419. };
  75420. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75421. var _this = this;
  75422. var numSamples = this.samples;
  75423. this._sampleSphere = this._generateHemisphere();
  75424. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  75425. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75426. "base", "range", "projection", "near", "far", "texelSize",
  75427. "xViewport", "yViewport", "maxZ", "minZAspect"
  75428. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75429. this._ssaoPostProcess.onApply = function (effect) {
  75430. if (_this._firstUpdate) {
  75431. effect.setArray3("sampleSphere", _this._sampleSphere);
  75432. effect.setFloat("randTextureTiles", 4.0);
  75433. }
  75434. if (!_this._scene.activeCamera) {
  75435. return;
  75436. }
  75437. effect.setFloat("samplesFactor", 1 / _this.samples);
  75438. effect.setFloat("totalStrength", _this.totalStrength);
  75439. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  75440. effect.setFloat("radius", _this.radius);
  75441. effect.setFloat("maxZ", _this.maxZ);
  75442. effect.setFloat("minZAspect", _this.minZAspect);
  75443. effect.setFloat("base", _this.base);
  75444. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75445. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75446. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  75447. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  75448. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  75449. effect.setTexture("textureSampler", _this._depthTexture);
  75450. effect.setTexture("normalSampler", _this._normalTexture);
  75451. effect.setTexture("randomSampler", _this._randomTexture);
  75452. };
  75453. };
  75454. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75455. var _this = this;
  75456. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75457. this._ssaoCombinePostProcess.onApply = function (effect) {
  75458. var viewport = _this._scene.activeCamera.viewport;
  75459. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  75460. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75461. };
  75462. };
  75463. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  75464. var size = 512;
  75465. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75466. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75467. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75468. var context = this._randomTexture.getContext();
  75469. var rand = function (min, max) {
  75470. return Math.random() * (max - min) + min;
  75471. };
  75472. var randVector = BABYLON.Vector3.Zero();
  75473. for (var x = 0; x < size; x++) {
  75474. for (var y = 0; y < size; y++) {
  75475. randVector.x = rand(0.0, 1.0);
  75476. randVector.y = rand(0.0, 1.0);
  75477. randVector.z = 0.0;
  75478. randVector.normalize();
  75479. randVector.scaleInPlace(255);
  75480. randVector.x = Math.floor(randVector.x);
  75481. randVector.y = Math.floor(randVector.y);
  75482. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75483. context.fillRect(x, y, 1, 1);
  75484. }
  75485. }
  75486. this._randomTexture.update(false);
  75487. };
  75488. /**
  75489. * Serialize the rendering pipeline (Used when exporting)
  75490. * @returns the serialized object
  75491. */
  75492. SSAO2RenderingPipeline.prototype.serialize = function () {
  75493. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75494. serializationObject.customType = "SSAO2RenderingPipeline";
  75495. return serializationObject;
  75496. };
  75497. /**
  75498. * Parse the serialized pipeline
  75499. * @param source Source pipeline.
  75500. * @param scene The scene to load the pipeline to.
  75501. * @param rootUrl The URL of the serialized pipeline.
  75502. * @returns An instantiated pipeline from the serialized object.
  75503. */
  75504. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  75505. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75506. };
  75507. __decorate([
  75508. BABYLON.serialize()
  75509. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  75510. __decorate([
  75511. BABYLON.serialize()
  75512. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  75513. __decorate([
  75514. BABYLON.serialize()
  75515. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  75516. __decorate([
  75517. BABYLON.serialize("samples")
  75518. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  75519. __decorate([
  75520. BABYLON.serialize()
  75521. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  75522. __decorate([
  75523. BABYLON.serialize("expensiveBlur")
  75524. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  75525. __decorate([
  75526. BABYLON.serialize()
  75527. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  75528. __decorate([
  75529. BABYLON.serialize()
  75530. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  75531. return SSAO2RenderingPipeline;
  75532. }(BABYLON.PostProcessRenderPipeline));
  75533. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  75534. })(BABYLON || (BABYLON = {}));
  75535. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  75536. // BABYLON.JS Chromatic Aberration GLSL Shader
  75537. // Author: Olivier Guyot
  75538. // Separates very slightly R, G and B colors on the edges of the screen
  75539. // Inspired by Francois Tarlier & Martins Upitis
  75540. var BABYLON;
  75541. (function (BABYLON) {
  75542. var LensRenderingPipeline = /** @class */ (function (_super) {
  75543. __extends(LensRenderingPipeline, _super);
  75544. /**
  75545. * @constructor
  75546. *
  75547. * Effect parameters are as follow:
  75548. * {
  75549. * chromatic_aberration: number; // from 0 to x (1 for realism)
  75550. * edge_blur: number; // from 0 to x (1 for realism)
  75551. * distortion: number; // from 0 to x (1 for realism)
  75552. * grain_amount: number; // from 0 to 1
  75553. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  75554. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  75555. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  75556. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  75557. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  75558. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  75559. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  75560. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  75561. * }
  75562. * Note: if an effect parameter is unset, effect is disabled
  75563. *
  75564. * @param {string} name - The rendering pipeline name
  75565. * @param {object} parameters - An object containing all parameters (see above)
  75566. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75567. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  75568. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75569. */
  75570. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  75571. if (ratio === void 0) { ratio = 1.0; }
  75572. var _this = _super.call(this, scene.getEngine(), name) || this;
  75573. // Lens effects can be of the following:
  75574. // - chromatic aberration (slight shift of RGB colors)
  75575. // - blur on the edge of the lens
  75576. // - lens distortion
  75577. // - depth-of-field blur & highlights enhancing
  75578. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  75579. // - grain effect (noise or custom texture)
  75580. // Two additional texture samplers are needed:
  75581. // - depth map (for depth-of-field)
  75582. // - grain texture
  75583. /**
  75584. * The chromatic aberration PostProcess id in the pipeline
  75585. */
  75586. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  75587. /**
  75588. * The highlights enhancing PostProcess id in the pipeline
  75589. */
  75590. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  75591. /**
  75592. * The depth-of-field PostProcess id in the pipeline
  75593. */
  75594. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  75595. _this._scene = scene;
  75596. // Fetch texture samplers
  75597. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75598. if (parameters.grain_texture) {
  75599. _this._grainTexture = parameters.grain_texture;
  75600. }
  75601. else {
  75602. _this._createGrainTexture();
  75603. }
  75604. // save parameters
  75605. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  75606. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  75607. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  75608. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  75609. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  75610. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  75611. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  75612. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  75613. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  75614. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  75615. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  75616. // Create effects
  75617. _this._createChromaticAberrationPostProcess(ratio);
  75618. _this._createHighlightsPostProcess(ratio);
  75619. _this._createDepthOfFieldPostProcess(ratio / 4);
  75620. // Set up pipeline
  75621. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  75622. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  75623. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  75624. if (_this._highlightsGain === -1) {
  75625. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  75626. }
  75627. // Finish
  75628. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75629. if (cameras) {
  75630. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75631. }
  75632. return _this;
  75633. }
  75634. // public methods (self explanatory)
  75635. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  75636. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  75637. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  75638. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  75639. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  75640. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  75641. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  75642. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  75643. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  75644. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  75645. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  75646. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  75647. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  75648. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  75649. };
  75650. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  75651. this._highlightsPostProcess.updateEffect();
  75652. };
  75653. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  75654. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  75655. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  75656. this._highlightsGain = amount;
  75657. };
  75658. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  75659. if (this._highlightsGain === -1) {
  75660. this._highlightsGain = 1.0;
  75661. }
  75662. this._highlightsThreshold = amount;
  75663. };
  75664. LensRenderingPipeline.prototype.disableHighlights = function () {
  75665. this._highlightsGain = -1;
  75666. };
  75667. /**
  75668. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  75669. */
  75670. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75671. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75672. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75673. this._chromaticAberrationPostProcess = null;
  75674. this._highlightsPostProcess = null;
  75675. this._depthOfFieldPostProcess = null;
  75676. this._grainTexture.dispose();
  75677. if (disableDepthRender)
  75678. this._scene.disableDepthRenderer();
  75679. };
  75680. // colors shifting and distortion
  75681. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  75682. var _this = this;
  75683. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  75684. [], // samplers
  75685. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75686. this._chromaticAberrationPostProcess.onApply = function (effect) {
  75687. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  75688. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75689. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75690. effect.setFloat('radialIntensity', 1);
  75691. effect.setFloat2('direction', 17, 17);
  75692. effect.setFloat2('centerPosition', 0.5, 0.5);
  75693. };
  75694. };
  75695. // highlights enhancing
  75696. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  75697. var _this = this;
  75698. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  75699. [], // samplers
  75700. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  75701. this._highlightsPostProcess.onApply = function (effect) {
  75702. effect.setFloat('gain', _this._highlightsGain);
  75703. effect.setFloat('threshold', _this._highlightsThreshold);
  75704. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  75705. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75706. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75707. };
  75708. };
  75709. // colors shifting and distortion
  75710. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  75711. var _this = this;
  75712. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  75713. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  75714. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  75715. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75716. this._depthOfFieldPostProcess.onApply = function (effect) {
  75717. effect.setTexture("depthSampler", _this._depthTexture);
  75718. effect.setTexture("grainSampler", _this._grainTexture);
  75719. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  75720. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  75721. effect.setFloat('grain_amount', _this._grainAmount);
  75722. effect.setBool('blur_noise', _this._blurNoise);
  75723. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75724. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75725. effect.setFloat('distortion', _this._distortion);
  75726. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  75727. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  75728. effect.setFloat('aperture', _this._dofAperture);
  75729. effect.setFloat('darken', _this._dofDarken);
  75730. effect.setFloat('edge_blur', _this._edgeBlur);
  75731. effect.setBool('highlights', (_this._highlightsGain !== -1));
  75732. if (_this._scene.activeCamera) {
  75733. effect.setFloat('near', _this._scene.activeCamera.minZ);
  75734. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  75735. }
  75736. };
  75737. };
  75738. // creates a black and white random noise texture, 512x512
  75739. LensRenderingPipeline.prototype._createGrainTexture = function () {
  75740. var size = 512;
  75741. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75742. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75743. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75744. var context = this._grainTexture.getContext();
  75745. var rand = function (min, max) {
  75746. return Math.random() * (max - min) + min;
  75747. };
  75748. var value;
  75749. for (var x = 0; x < size; x++) {
  75750. for (var y = 0; y < size; y++) {
  75751. value = Math.floor(rand(0.42, 0.58) * 255);
  75752. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  75753. context.fillRect(x, y, 1, 1);
  75754. }
  75755. }
  75756. this._grainTexture.update(false);
  75757. };
  75758. return LensRenderingPipeline;
  75759. }(BABYLON.PostProcessRenderPipeline));
  75760. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  75761. })(BABYLON || (BABYLON = {}));
  75762. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  75763. var BABYLON;
  75764. (function (BABYLON) {
  75765. var StandardRenderingPipeline = /** @class */ (function (_super) {
  75766. __extends(StandardRenderingPipeline, _super);
  75767. /**
  75768. * @constructor
  75769. * @param {string} name - The rendering pipeline name
  75770. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75771. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  75772. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  75773. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75774. */
  75775. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  75776. if (originalPostProcess === void 0) { originalPostProcess = null; }
  75777. var _this = _super.call(this, scene.getEngine(), name) || this;
  75778. _this.downSampleX4PostProcess = null;
  75779. _this.brightPassPostProcess = null;
  75780. _this.blurHPostProcesses = [];
  75781. _this.blurVPostProcesses = [];
  75782. _this.textureAdderPostProcess = null;
  75783. _this.volumetricLightPostProcess = null;
  75784. _this.volumetricLightSmoothXPostProcess = null;
  75785. _this.volumetricLightSmoothYPostProcess = null;
  75786. _this.volumetricLightMergePostProces = null;
  75787. _this.volumetricLightFinalPostProcess = null;
  75788. _this.luminancePostProcess = null;
  75789. _this.luminanceDownSamplePostProcesses = [];
  75790. _this.hdrPostProcess = null;
  75791. _this.textureAdderFinalPostProcess = null;
  75792. _this.lensFlareFinalPostProcess = null;
  75793. _this.hdrFinalPostProcess = null;
  75794. _this.lensFlarePostProcess = null;
  75795. _this.lensFlareComposePostProcess = null;
  75796. _this.motionBlurPostProcess = null;
  75797. _this.depthOfFieldPostProcess = null;
  75798. // Values
  75799. _this.brightThreshold = 1.0;
  75800. _this.blurWidth = 512.0;
  75801. _this.horizontalBlur = false;
  75802. _this.exposure = 1.0;
  75803. _this.lensTexture = null;
  75804. _this.volumetricLightCoefficient = 0.2;
  75805. _this.volumetricLightPower = 4.0;
  75806. _this.volumetricLightBlurScale = 64.0;
  75807. _this.sourceLight = null;
  75808. _this.hdrMinimumLuminance = 1.0;
  75809. _this.hdrDecreaseRate = 0.5;
  75810. _this.hdrIncreaseRate = 0.5;
  75811. _this.lensColorTexture = null;
  75812. _this.lensFlareStrength = 20.0;
  75813. _this.lensFlareGhostDispersal = 1.4;
  75814. _this.lensFlareHaloWidth = 0.7;
  75815. _this.lensFlareDistortionStrength = 16.0;
  75816. _this.lensStarTexture = null;
  75817. _this.lensFlareDirtTexture = null;
  75818. _this.depthOfFieldDistance = 10.0;
  75819. _this.depthOfFieldBlurWidth = 64.0;
  75820. _this.motionStrength = 1.0;
  75821. // IAnimatable
  75822. _this.animations = [];
  75823. _this._currentDepthOfFieldSource = null;
  75824. _this._hdrCurrentLuminance = 1.0;
  75825. // Getters and setters
  75826. _this._bloomEnabled = true;
  75827. _this._depthOfFieldEnabled = false;
  75828. _this._vlsEnabled = false;
  75829. _this._lensFlareEnabled = false;
  75830. _this._hdrEnabled = false;
  75831. _this._motionBlurEnabled = false;
  75832. _this._motionBlurSamples = 64.0;
  75833. _this._volumetricLightStepsCount = 50.0;
  75834. _this._cameras = cameras || [];
  75835. // Initialize
  75836. _this._scene = scene;
  75837. _this._basePostProcess = originalPostProcess;
  75838. _this._ratio = ratio;
  75839. // Misc
  75840. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75841. // Finish
  75842. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75843. _this._buildPipeline();
  75844. return _this;
  75845. }
  75846. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  75847. get: function () {
  75848. return this._bloomEnabled;
  75849. },
  75850. set: function (enabled) {
  75851. if (this._bloomEnabled === enabled) {
  75852. return;
  75853. }
  75854. this._bloomEnabled = enabled;
  75855. this._buildPipeline();
  75856. },
  75857. enumerable: true,
  75858. configurable: true
  75859. });
  75860. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  75861. get: function () {
  75862. return this._depthOfFieldEnabled;
  75863. },
  75864. set: function (enabled) {
  75865. if (this._depthOfFieldEnabled === enabled) {
  75866. return;
  75867. }
  75868. this._depthOfFieldEnabled = enabled;
  75869. this._buildPipeline();
  75870. },
  75871. enumerable: true,
  75872. configurable: true
  75873. });
  75874. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  75875. get: function () {
  75876. return this._lensFlareEnabled;
  75877. },
  75878. set: function (enabled) {
  75879. if (this._lensFlareEnabled === enabled) {
  75880. return;
  75881. }
  75882. this._lensFlareEnabled = enabled;
  75883. this._buildPipeline();
  75884. },
  75885. enumerable: true,
  75886. configurable: true
  75887. });
  75888. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  75889. get: function () {
  75890. return this._hdrEnabled;
  75891. },
  75892. set: function (enabled) {
  75893. if (this._hdrEnabled === enabled) {
  75894. return;
  75895. }
  75896. this._hdrEnabled = enabled;
  75897. this._buildPipeline();
  75898. },
  75899. enumerable: true,
  75900. configurable: true
  75901. });
  75902. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  75903. get: function () {
  75904. return this._vlsEnabled;
  75905. },
  75906. set: function (enabled) {
  75907. if (this._vlsEnabled === enabled) {
  75908. return;
  75909. }
  75910. if (enabled) {
  75911. var geometry = this._scene.enableGeometryBufferRenderer();
  75912. if (!geometry) {
  75913. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  75914. return;
  75915. }
  75916. }
  75917. this._vlsEnabled = enabled;
  75918. this._buildPipeline();
  75919. },
  75920. enumerable: true,
  75921. configurable: true
  75922. });
  75923. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  75924. get: function () {
  75925. return this._motionBlurEnabled;
  75926. },
  75927. set: function (enabled) {
  75928. if (this._motionBlurEnabled === enabled) {
  75929. return;
  75930. }
  75931. this._motionBlurEnabled = enabled;
  75932. this._buildPipeline();
  75933. },
  75934. enumerable: true,
  75935. configurable: true
  75936. });
  75937. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  75938. get: function () {
  75939. return this._volumetricLightStepsCount;
  75940. },
  75941. set: function (count) {
  75942. if (this.volumetricLightPostProcess) {
  75943. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  75944. }
  75945. this._volumetricLightStepsCount = count;
  75946. },
  75947. enumerable: true,
  75948. configurable: true
  75949. });
  75950. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  75951. get: function () {
  75952. return this._motionBlurSamples;
  75953. },
  75954. set: function (samples) {
  75955. if (this.motionBlurPostProcess) {
  75956. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  75957. }
  75958. this._motionBlurSamples = samples;
  75959. },
  75960. enumerable: true,
  75961. configurable: true
  75962. });
  75963. StandardRenderingPipeline.prototype._buildPipeline = function () {
  75964. var _this = this;
  75965. var ratio = this._ratio;
  75966. var scene = this._scene;
  75967. this._disposePostProcesses();
  75968. this._reset();
  75969. // Create pass post-process
  75970. if (!this._basePostProcess) {
  75971. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  75972. this.originalPostProcess.onApply = function (effect) {
  75973. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  75974. };
  75975. }
  75976. else {
  75977. this.originalPostProcess = this._basePostProcess;
  75978. }
  75979. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  75980. this._currentDepthOfFieldSource = this.originalPostProcess;
  75981. if (this._bloomEnabled) {
  75982. // Create down sample X4 post-process
  75983. this._createDownSampleX4PostProcess(scene, ratio / 2);
  75984. // Create bright pass post-process
  75985. this._createBrightPassPostProcess(scene, ratio / 2);
  75986. // Create gaussian blur post-processes (down sampling blurs)
  75987. this._createBlurPostProcesses(scene, ratio / 4, 1);
  75988. // Create texture adder post-process
  75989. this._createTextureAdderPostProcess(scene, ratio);
  75990. // Create depth-of-field source post-process
  75991. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75992. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  75993. }
  75994. if (this._vlsEnabled) {
  75995. // Create volumetric light
  75996. this._createVolumetricLightPostProcess(scene, ratio);
  75997. // Create volumetric light final post-process
  75998. this.volumetricLightFinalPostProcess = new BABYLON.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  76000. }
  76001. if (this._lensFlareEnabled) {
  76002. // Create lens flare post-process
  76003. this._createLensFlarePostProcess(scene, ratio);
  76004. // Create depth-of-field source post-process post lens-flare and disable it now
  76005. this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76006. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  76007. }
  76008. if (this._hdrEnabled) {
  76009. // Create luminance
  76010. this._createLuminancePostProcesses(scene, this._floatTextureType);
  76011. // Create HDR
  76012. this._createHdrPostProcess(scene, ratio);
  76013. // Create depth-of-field source post-process post hdr and disable it now
  76014. this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76015. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  76016. }
  76017. if (this._depthOfFieldEnabled) {
  76018. // Create gaussian blur used by depth-of-field
  76019. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  76020. // Create depth-of-field post-process
  76021. this._createDepthOfFieldPostProcess(scene, ratio);
  76022. }
  76023. if (this._motionBlurEnabled) {
  76024. // Create motion blur post-process
  76025. this._createMotionBlurPostProcess(scene, ratio);
  76026. }
  76027. if (this._cameras !== null) {
  76028. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76029. }
  76030. };
  76031. // Down Sample X4 Post-Processs
  76032. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  76033. var _this = this;
  76034. var downSampleX4Offsets = new Array(32);
  76035. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76036. this.downSampleX4PostProcess.onApply = function (effect) {
  76037. var id = 0;
  76038. var width = _this.downSampleX4PostProcess.width;
  76039. var height = _this.downSampleX4PostProcess.height;
  76040. for (var i = -2; i < 2; i++) {
  76041. for (var j = -2; j < 2; j++) {
  76042. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  76043. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  76044. id += 2;
  76045. }
  76046. }
  76047. effect.setArray2("dsOffsets", downSampleX4Offsets);
  76048. };
  76049. // Add to pipeline
  76050. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  76051. };
  76052. // Brightpass Post-Process
  76053. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  76054. var _this = this;
  76055. var brightOffsets = new Array(8);
  76056. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76057. this.brightPassPostProcess.onApply = function (effect) {
  76058. var sU = (1.0 / _this.brightPassPostProcess.width);
  76059. var sV = (1.0 / _this.brightPassPostProcess.height);
  76060. brightOffsets[0] = -0.5 * sU;
  76061. brightOffsets[1] = 0.5 * sV;
  76062. brightOffsets[2] = 0.5 * sU;
  76063. brightOffsets[3] = 0.5 * sV;
  76064. brightOffsets[4] = -0.5 * sU;
  76065. brightOffsets[5] = -0.5 * sV;
  76066. brightOffsets[6] = 0.5 * sU;
  76067. brightOffsets[7] = -0.5 * sV;
  76068. effect.setArray2("dsOffsets", brightOffsets);
  76069. effect.setFloat("brightThreshold", _this.brightThreshold);
  76070. };
  76071. // Add to pipeline
  76072. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  76073. };
  76074. // Create blur H&V post-processes
  76075. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  76076. var _this = this;
  76077. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  76078. var engine = scene.getEngine();
  76079. var blurX = new BABYLON.BlurPostProcess("HDRBlurH" + "_" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76080. var blurY = new BABYLON.BlurPostProcess("HDRBlurV" + "_" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76081. blurX.onActivateObservable.add(function () {
  76082. var dw = blurX.width / engine.getRenderWidth();
  76083. blurX.kernel = _this[blurWidthKey] * dw;
  76084. });
  76085. blurY.onActivateObservable.add(function () {
  76086. var dw = blurY.height / engine.getRenderHeight();
  76087. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  76088. });
  76089. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  76090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  76091. this.blurHPostProcesses.push(blurX);
  76092. this.blurVPostProcesses.push(blurY);
  76093. };
  76094. // Create texture adder post-process
  76095. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  76096. var _this = this;
  76097. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76098. this.textureAdderPostProcess.onApply = function (effect) {
  76099. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  76100. effect.setTexture("lensSampler", _this.lensTexture);
  76101. effect.setFloat("exposure", _this.exposure);
  76102. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  76103. };
  76104. // Add to pipeline
  76105. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  76106. };
  76107. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  76108. var _this = this;
  76109. var geometryRenderer = scene.enableGeometryBufferRenderer();
  76110. geometryRenderer.enablePosition = true;
  76111. var geometry = geometryRenderer.getGBuffer();
  76112. // Base post-process
  76113. this.volumetricLightPostProcess = new BABYLON.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
  76114. var depthValues = BABYLON.Vector2.Zero();
  76115. this.volumetricLightPostProcess.onApply = function (effect) {
  76116. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  76117. var generator = _this.sourceLight.getShadowGenerator();
  76118. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  76119. effect.setTexture("positionSampler", geometry.textures[2]);
  76120. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  76121. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  76122. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  76123. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  76124. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  76125. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  76126. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  76127. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  76128. effect.setVector2("depthValues", depthValues);
  76129. }
  76130. };
  76131. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  76132. // Smooth
  76133. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  76134. // Merge
  76135. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  76136. this.volumetricLightMergePostProces.onApply = function (effect) {
  76137. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  76138. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  76139. };
  76140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  76141. };
  76142. // Create luminance
  76143. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  76144. var _this = this;
  76145. // Create luminance
  76146. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  76147. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  76148. var offsets = [];
  76149. this.luminancePostProcess.onApply = function (effect) {
  76150. var sU = (1.0 / _this.luminancePostProcess.width);
  76151. var sV = (1.0 / _this.luminancePostProcess.height);
  76152. offsets[0] = -0.5 * sU;
  76153. offsets[1] = 0.5 * sV;
  76154. offsets[2] = 0.5 * sU;
  76155. offsets[3] = 0.5 * sV;
  76156. offsets[4] = -0.5 * sU;
  76157. offsets[5] = -0.5 * sV;
  76158. offsets[6] = 0.5 * sU;
  76159. offsets[7] = -0.5 * sV;
  76160. effect.setArray2("lumOffsets", offsets);
  76161. };
  76162. // Add to pipeline
  76163. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  76164. // Create down sample luminance
  76165. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  76166. var size = Math.pow(3, i);
  76167. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  76168. if (i === 0) {
  76169. defines += "#define FINAL_DOWN_SAMPLER";
  76170. }
  76171. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  76172. this.luminanceDownSamplePostProcesses.push(postProcess);
  76173. }
  76174. // Create callbacks and add effects
  76175. var lastLuminance = this.luminancePostProcess;
  76176. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  76177. var downSampleOffsets = new Array(18);
  76178. pp.onApply = function (effect) {
  76179. if (!lastLuminance) {
  76180. return;
  76181. }
  76182. var id = 0;
  76183. for (var x = -1; x < 2; x++) {
  76184. for (var y = -1; y < 2; y++) {
  76185. downSampleOffsets[id] = x / lastLuminance.width;
  76186. downSampleOffsets[id + 1] = y / lastLuminance.height;
  76187. id += 2;
  76188. }
  76189. }
  76190. effect.setArray2("dsOffsets", downSampleOffsets);
  76191. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  76192. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76193. lastLuminance = _this.luminancePostProcess;
  76194. }
  76195. else {
  76196. lastLuminance = pp;
  76197. }
  76198. };
  76199. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76200. pp.onAfterRender = function (effect) {
  76201. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  76202. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  76203. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  76204. };
  76205. }
  76206. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  76207. });
  76208. };
  76209. // Create HDR post-process
  76210. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  76211. var _this = this;
  76212. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76213. var outputLiminance = 1;
  76214. var time = 0;
  76215. var lastTime = 0;
  76216. this.hdrPostProcess.onApply = function (effect) {
  76217. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  76218. time += scene.getEngine().getDeltaTime();
  76219. if (outputLiminance < 0) {
  76220. outputLiminance = _this._hdrCurrentLuminance;
  76221. }
  76222. else {
  76223. var dt = (lastTime - time) / 1000.0;
  76224. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  76225. outputLiminance += _this.hdrDecreaseRate * dt;
  76226. }
  76227. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  76228. outputLiminance -= _this.hdrIncreaseRate * dt;
  76229. }
  76230. else {
  76231. outputLiminance = _this._hdrCurrentLuminance;
  76232. }
  76233. }
  76234. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  76235. effect.setFloat("averageLuminance", outputLiminance);
  76236. lastTime = time;
  76237. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  76238. };
  76239. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  76240. };
  76241. // Create lens flare post-process
  76242. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  76243. var _this = this;
  76244. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76245. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  76246. this._createBlurPostProcesses(scene, ratio / 4, 2);
  76247. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  76249. var resolution = new BABYLON.Vector2(0, 0);
  76250. // Lens flare
  76251. this.lensFlarePostProcess.onApply = function (effect) {
  76252. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  76253. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  76254. effect.setFloat("strength", _this.lensFlareStrength);
  76255. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  76256. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  76257. // Shift
  76258. resolution.x = _this.lensFlarePostProcess.width;
  76259. resolution.y = _this.lensFlarePostProcess.height;
  76260. effect.setVector2("resolution", resolution);
  76261. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  76262. };
  76263. // Compose
  76264. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  76265. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  76266. this.lensFlareComposePostProcess.onApply = function (effect) {
  76267. if (!_this._scene.activeCamera) {
  76268. return;
  76269. }
  76270. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76271. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  76272. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  76273. // Lens start rotation matrix
  76274. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  76275. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  76276. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  76277. camRot *= 4.0;
  76278. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  76279. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  76280. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  76281. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  76282. };
  76283. };
  76284. // Create depth-of-field post-process
  76285. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  76286. var _this = this;
  76287. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76288. this.depthOfFieldPostProcess.onApply = function (effect) {
  76289. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76290. effect.setTexture("depthSampler", _this._getDepthTexture());
  76291. effect.setFloat("distance", _this.depthOfFieldDistance);
  76292. };
  76293. // Add to pipeline
  76294. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  76295. };
  76296. // Create motion blur post-process
  76297. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  76298. var _this = this;
  76299. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76300. var motionScale = 0;
  76301. var prevViewProjection = BABYLON.Matrix.Identity();
  76302. var invViewProjection = BABYLON.Matrix.Identity();
  76303. var viewProjection = BABYLON.Matrix.Identity();
  76304. var screenSize = BABYLON.Vector2.Zero();
  76305. this.motionBlurPostProcess.onApply = function (effect) {
  76306. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  76307. viewProjection.invertToRef(invViewProjection);
  76308. effect.setMatrix("inverseViewProjection", invViewProjection);
  76309. effect.setMatrix("prevViewProjection", prevViewProjection);
  76310. prevViewProjection = viewProjection;
  76311. screenSize.x = _this.motionBlurPostProcess.width;
  76312. screenSize.y = _this.motionBlurPostProcess.height;
  76313. effect.setVector2("screenSize", screenSize);
  76314. motionScale = scene.getEngine().getFps() / 60.0;
  76315. effect.setFloat("motionScale", motionScale);
  76316. effect.setFloat("motionStrength", _this.motionStrength);
  76317. effect.setTexture("depthSampler", _this._getDepthTexture());
  76318. };
  76319. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  76320. };
  76321. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  76322. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  76323. var renderer = this._scene.enableGeometryBufferRenderer();
  76324. return renderer.getGBuffer().textures[0];
  76325. }
  76326. return this._scene.enableDepthRenderer().getDepthMap();
  76327. };
  76328. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  76329. for (var i = 0; i < this._cameras.length; i++) {
  76330. var camera = this._cameras[i];
  76331. if (this.originalPostProcess) {
  76332. this.originalPostProcess.dispose(camera);
  76333. }
  76334. if (this.downSampleX4PostProcess) {
  76335. this.downSampleX4PostProcess.dispose(camera);
  76336. }
  76337. if (this.brightPassPostProcess) {
  76338. this.brightPassPostProcess.dispose(camera);
  76339. }
  76340. if (this.textureAdderPostProcess) {
  76341. this.textureAdderPostProcess.dispose(camera);
  76342. }
  76343. if (this.textureAdderFinalPostProcess) {
  76344. this.textureAdderFinalPostProcess.dispose(camera);
  76345. }
  76346. if (this.volumetricLightPostProcess) {
  76347. this.volumetricLightPostProcess.dispose(camera);
  76348. }
  76349. if (this.volumetricLightSmoothXPostProcess) {
  76350. this.volumetricLightSmoothXPostProcess.dispose(camera);
  76351. }
  76352. if (this.volumetricLightSmoothYPostProcess) {
  76353. this.volumetricLightSmoothYPostProcess.dispose(camera);
  76354. }
  76355. if (this.volumetricLightMergePostProces) {
  76356. this.volumetricLightMergePostProces.dispose(camera);
  76357. }
  76358. if (this.volumetricLightFinalPostProcess) {
  76359. this.volumetricLightFinalPostProcess.dispose(camera);
  76360. }
  76361. if (this.lensFlarePostProcess) {
  76362. this.lensFlarePostProcess.dispose(camera);
  76363. }
  76364. if (this.lensFlareComposePostProcess) {
  76365. this.lensFlareComposePostProcess.dispose(camera);
  76366. }
  76367. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  76368. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  76369. }
  76370. if (this.luminancePostProcess) {
  76371. this.luminancePostProcess.dispose(camera);
  76372. }
  76373. if (this.hdrPostProcess) {
  76374. this.hdrPostProcess.dispose(camera);
  76375. }
  76376. if (this.hdrFinalPostProcess) {
  76377. this.hdrFinalPostProcess.dispose(camera);
  76378. }
  76379. if (this.depthOfFieldPostProcess) {
  76380. this.depthOfFieldPostProcess.dispose(camera);
  76381. }
  76382. if (this.motionBlurPostProcess) {
  76383. this.motionBlurPostProcess.dispose(camera);
  76384. }
  76385. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  76386. this.blurHPostProcesses[j].dispose(camera);
  76387. }
  76388. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  76389. this.blurVPostProcesses[j].dispose(camera);
  76390. }
  76391. }
  76392. this.originalPostProcess = null;
  76393. this.downSampleX4PostProcess = null;
  76394. this.brightPassPostProcess = null;
  76395. this.textureAdderPostProcess = null;
  76396. this.textureAdderFinalPostProcess = null;
  76397. this.volumetricLightPostProcess = null;
  76398. this.volumetricLightSmoothXPostProcess = null;
  76399. this.volumetricLightSmoothYPostProcess = null;
  76400. this.volumetricLightMergePostProces = null;
  76401. this.volumetricLightFinalPostProcess = null;
  76402. this.lensFlarePostProcess = null;
  76403. this.lensFlareComposePostProcess = null;
  76404. this.luminancePostProcess = null;
  76405. this.hdrPostProcess = null;
  76406. this.hdrFinalPostProcess = null;
  76407. this.depthOfFieldPostProcess = null;
  76408. this.motionBlurPostProcess = null;
  76409. this.luminanceDownSamplePostProcesses = [];
  76410. this.blurHPostProcesses = [];
  76411. this.blurVPostProcesses = [];
  76412. };
  76413. /**
  76414. * Dispose of the pipeline and stop all post processes
  76415. */
  76416. StandardRenderingPipeline.prototype.dispose = function () {
  76417. this._disposePostProcesses();
  76418. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76419. _super.prototype.dispose.call(this);
  76420. };
  76421. /**
  76422. * Serialize the rendering pipeline (Used when exporting)
  76423. * @returns the serialized object
  76424. */
  76425. StandardRenderingPipeline.prototype.serialize = function () {
  76426. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76427. if (this.sourceLight) {
  76428. serializationObject.sourceLightId = this.sourceLight.id;
  76429. }
  76430. serializationObject.customType = "StandardRenderingPipeline";
  76431. return serializationObject;
  76432. };
  76433. /**
  76434. * Parse the serialized pipeline
  76435. * @param source Source pipeline.
  76436. * @param scene The scene to load the pipeline to.
  76437. * @param rootUrl The URL of the serialized pipeline.
  76438. * @returns An instantiated pipeline from the serialized object.
  76439. */
  76440. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76441. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76442. if (source.sourceLightId) {
  76443. p.sourceLight = scene.getLightByID(source.sourceLightId);
  76444. }
  76445. return p;
  76446. };
  76447. // Luminance steps
  76448. StandardRenderingPipeline.LuminanceSteps = 6;
  76449. __decorate([
  76450. BABYLON.serialize()
  76451. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  76452. __decorate([
  76453. BABYLON.serialize()
  76454. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  76455. __decorate([
  76456. BABYLON.serialize()
  76457. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  76458. __decorate([
  76459. BABYLON.serialize()
  76460. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  76461. __decorate([
  76462. BABYLON.serializeAsTexture("lensTexture")
  76463. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  76464. __decorate([
  76465. BABYLON.serialize()
  76466. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  76467. __decorate([
  76468. BABYLON.serialize()
  76469. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  76470. __decorate([
  76471. BABYLON.serialize()
  76472. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  76473. __decorate([
  76474. BABYLON.serialize()
  76475. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  76476. __decorate([
  76477. BABYLON.serialize()
  76478. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  76479. __decorate([
  76480. BABYLON.serialize()
  76481. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  76482. __decorate([
  76483. BABYLON.serializeAsTexture("lensColorTexture")
  76484. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  76485. __decorate([
  76486. BABYLON.serialize()
  76487. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  76488. __decorate([
  76489. BABYLON.serialize()
  76490. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  76491. __decorate([
  76492. BABYLON.serialize()
  76493. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  76494. __decorate([
  76495. BABYLON.serialize()
  76496. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  76497. __decorate([
  76498. BABYLON.serializeAsTexture("lensStarTexture")
  76499. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  76500. __decorate([
  76501. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  76502. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  76503. __decorate([
  76504. BABYLON.serialize()
  76505. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  76506. __decorate([
  76507. BABYLON.serialize()
  76508. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  76509. __decorate([
  76510. BABYLON.serialize()
  76511. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  76512. __decorate([
  76513. BABYLON.serialize()
  76514. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  76515. __decorate([
  76516. BABYLON.serialize()
  76517. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  76518. __decorate([
  76519. BABYLON.serialize()
  76520. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  76521. __decorate([
  76522. BABYLON.serialize()
  76523. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  76524. __decorate([
  76525. BABYLON.serialize()
  76526. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  76527. __decorate([
  76528. BABYLON.serialize()
  76529. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  76530. __decorate([
  76531. BABYLON.serialize()
  76532. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  76533. __decorate([
  76534. BABYLON.serialize()
  76535. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  76536. __decorate([
  76537. BABYLON.serialize()
  76538. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  76539. return StandardRenderingPipeline;
  76540. }(BABYLON.PostProcessRenderPipeline));
  76541. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  76542. })(BABYLON || (BABYLON = {}));
  76543. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  76544. var BABYLON;
  76545. (function (BABYLON) {
  76546. var FxaaPostProcess = /** @class */ (function (_super) {
  76547. __extends(FxaaPostProcess, _super);
  76548. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76549. if (camera === void 0) { camera = null; }
  76550. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76551. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  76552. var defines = _this._getDefines();
  76553. _this.updateEffect(defines);
  76554. _this.onApplyObservable.add(function (effect) {
  76555. var texelSize = _this.texelSize;
  76556. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  76557. });
  76558. return _this;
  76559. }
  76560. FxaaPostProcess.prototype._getDefines = function () {
  76561. var engine = this.getEngine();
  76562. if (!engine) {
  76563. return null;
  76564. }
  76565. var glInfo = engine.getGlInfo();
  76566. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  76567. return "#define MALI 1\n";
  76568. }
  76569. return null;
  76570. };
  76571. return FxaaPostProcess;
  76572. }(BABYLON.PostProcess));
  76573. BABYLON.FxaaPostProcess = FxaaPostProcess;
  76574. })(BABYLON || (BABYLON = {}));
  76575. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  76576. var BABYLON;
  76577. (function (BABYLON) {
  76578. /**
  76579. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  76580. */
  76581. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  76582. __extends(ChromaticAberrationPostProcess, _super);
  76583. /**
  76584. * Creates a new instance ChromaticAberrationPostProcess
  76585. * @param name The name of the effect.
  76586. * @param screenWidth The width of the screen to apply the effect on.
  76587. * @param screenHeight The height of the screen to apply the effect on.
  76588. * @param options The required width/height ratio to downsize to before computing the render pass.
  76589. * @param camera The camera to apply the render pass to.
  76590. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76591. * @param engine The engine which the post process will be applied. (default: current engine)
  76592. * @param reusable If the post process can be reused on the same frame. (default: false)
  76593. * @param textureType Type of textures used when performing the post process. (default: 0)
  76594. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  76595. */
  76596. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76597. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76598. if (blockCompilation === void 0) { blockCompilation = false; }
  76599. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76600. /**
  76601. * The amount of seperation of rgb channels (default: 30)
  76602. */
  76603. _this.aberrationAmount = 30;
  76604. /**
  76605. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  76606. */
  76607. _this.radialIntensity = 0;
  76608. /**
  76609. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  76610. */
  76611. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  76612. /**
  76613. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  76614. */
  76615. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  76616. _this.onApplyObservable.add(function (effect) {
  76617. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  76618. effect.setFloat('screen_width', screenWidth);
  76619. effect.setFloat('screen_height', screenHeight);
  76620. effect.setFloat('radialIntensity', _this.radialIntensity);
  76621. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  76622. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  76623. });
  76624. return _this;
  76625. }
  76626. return ChromaticAberrationPostProcess;
  76627. }(BABYLON.PostProcess));
  76628. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  76629. })(BABYLON || (BABYLON = {}));
  76630. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  76631. var BABYLON;
  76632. (function (BABYLON) {
  76633. /**
  76634. * The GrainPostProcess adds noise to the image at mid luminance levels
  76635. */
  76636. var GrainPostProcess = /** @class */ (function (_super) {
  76637. __extends(GrainPostProcess, _super);
  76638. /**
  76639. * Creates a new instance of @see GrainPostProcess
  76640. * @param name The name of the effect.
  76641. * @param options The required width/height ratio to downsize to before computing the render pass.
  76642. * @param camera The camera to apply the render pass to.
  76643. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76644. * @param engine The engine which the post process will be applied. (default: current engine)
  76645. * @param reusable If the post process can be reused on the same frame. (default: false)
  76646. * @param textureType Type of textures used when performing the post process. (default: 0)
  76647. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  76648. */
  76649. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76650. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76651. if (blockCompilation === void 0) { blockCompilation = false; }
  76652. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76653. /**
  76654. * The intensity of the grain added (default: 30)
  76655. */
  76656. _this.intensity = 30;
  76657. /**
  76658. * If the grain should be randomized on every frame
  76659. */
  76660. _this.animated = false;
  76661. _this.onApplyObservable.add(function (effect) {
  76662. effect.setFloat('intensity', _this.intensity);
  76663. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  76664. });
  76665. return _this;
  76666. }
  76667. return GrainPostProcess;
  76668. }(BABYLON.PostProcess));
  76669. BABYLON.GrainPostProcess = GrainPostProcess;
  76670. })(BABYLON || (BABYLON = {}));
  76671. //# sourceMappingURL=babylon.grainPostProcess.js.map
  76672. var BABYLON;
  76673. (function (BABYLON) {
  76674. /**
  76675. * The SharpenPostProcess applies a sharpen kernel to every pixel
  76676. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76677. */
  76678. var SharpenPostProcess = /** @class */ (function (_super) {
  76679. __extends(SharpenPostProcess, _super);
  76680. /**
  76681. * Creates a new instance ConvolutionPostProcess
  76682. * @param name The name of the effect.
  76683. * @param options The required width/height ratio to downsize to before computing the render pass.
  76684. * @param camera The camera to apply the render pass to.
  76685. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76686. * @param engine The engine which the post process will be applied. (default: current engine)
  76687. * @param reusable If the post process can be reused on the same frame. (default: false)
  76688. * @param textureType Type of textures used when performing the post process. (default: 0)
  76689. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  76690. */
  76691. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76692. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76693. if (blockCompilation === void 0) { blockCompilation = false; }
  76694. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76695. /**
  76696. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  76697. */
  76698. _this.colorAmount = 1.0;
  76699. /**
  76700. * How much sharpness should be applied (default: 0.3)
  76701. */
  76702. _this.edgeAmount = 0.3;
  76703. _this.onApply = function (effect) {
  76704. effect.setFloat2("screenSize", _this.width, _this.height);
  76705. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  76706. };
  76707. return _this;
  76708. }
  76709. return SharpenPostProcess;
  76710. }(BABYLON.PostProcess));
  76711. BABYLON.SharpenPostProcess = SharpenPostProcess;
  76712. })(BABYLON || (BABYLON = {}));
  76713. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  76714. var BABYLON;
  76715. (function (BABYLON) {
  76716. /**
  76717. * The Blur Post Process which blurs an image based on a kernel and direction.
  76718. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  76719. */
  76720. var BlurPostProcess = /** @class */ (function (_super) {
  76721. __extends(BlurPostProcess, _super);
  76722. /**
  76723. * Creates a new instance BlurPostProcess
  76724. * @param name The name of the effect.
  76725. * @param direction The direction in which to blur the image.
  76726. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  76727. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  76728. * @param camera The camera to apply the render pass to.
  76729. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76730. * @param engine The engine which the post process will be applied. (default: current engine)
  76731. * @param reusable If the post process can be reused on the same frame. (default: false)
  76732. * @param textureType Type of textures used when performing the post process. (default: 0)
  76733. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  76734. */
  76735. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  76736. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76737. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76738. if (defines === void 0) { defines = ""; }
  76739. if (blockCompilation === void 0) { blockCompilation = false; }
  76740. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  76741. _this.direction = direction;
  76742. _this.blockCompilation = blockCompilation;
  76743. _this._packedFloat = false;
  76744. _this._staticDefines = "";
  76745. _this._staticDefines = defines;
  76746. _this.onApplyObservable.add(function (effect) {
  76747. if (_this._outputTexture) {
  76748. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  76749. }
  76750. else {
  76751. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  76752. }
  76753. });
  76754. _this.kernel = kernel;
  76755. return _this;
  76756. }
  76757. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  76758. /**
  76759. * Gets the length in pixels of the blur sample region
  76760. */
  76761. get: function () {
  76762. return this._idealKernel;
  76763. },
  76764. /**
  76765. * Sets the length in pixels of the blur sample region
  76766. */
  76767. set: function (v) {
  76768. if (this._idealKernel === v) {
  76769. return;
  76770. }
  76771. v = Math.max(v, 1);
  76772. this._idealKernel = v;
  76773. this._kernel = this._nearestBestKernel(v);
  76774. if (!this.blockCompilation) {
  76775. this._updateParameters();
  76776. }
  76777. },
  76778. enumerable: true,
  76779. configurable: true
  76780. });
  76781. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  76782. /**
  76783. * Gets wether or not the blur is unpacking/repacking floats
  76784. */
  76785. get: function () {
  76786. return this._packedFloat;
  76787. },
  76788. /**
  76789. * Sets wether or not the blur needs to unpack/repack floats
  76790. */
  76791. set: function (v) {
  76792. if (this._packedFloat === v) {
  76793. return;
  76794. }
  76795. this._packedFloat = v;
  76796. if (!this.blockCompilation) {
  76797. this._updateParameters();
  76798. }
  76799. },
  76800. enumerable: true,
  76801. configurable: true
  76802. });
  76803. /**
  76804. * Updates the effect with the current post process compile time values and recompiles the shader.
  76805. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76806. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76807. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76808. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  76809. * @param onCompiled Called when the shader has been compiled.
  76810. * @param onError Called if there is an error when compiling a shader.
  76811. */
  76812. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76813. if (defines === void 0) { defines = null; }
  76814. if (uniforms === void 0) { uniforms = null; }
  76815. if (samplers === void 0) { samplers = null; }
  76816. this._updateParameters(onCompiled, onError);
  76817. };
  76818. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  76819. // Generate sampling offsets and weights
  76820. var N = this._kernel;
  76821. var centerIndex = (N - 1) / 2;
  76822. // Generate Gaussian sampling weights over kernel
  76823. var offsets = [];
  76824. var weights = [];
  76825. var totalWeight = 0;
  76826. for (var i = 0; i < N; i++) {
  76827. var u = i / (N - 1);
  76828. var w = this._gaussianWeight(u * 2.0 - 1);
  76829. offsets[i] = (i - centerIndex);
  76830. weights[i] = w;
  76831. totalWeight += w;
  76832. }
  76833. // Normalize weights
  76834. for (var i = 0; i < weights.length; i++) {
  76835. weights[i] /= totalWeight;
  76836. }
  76837. // Optimize: combine samples to take advantage of hardware linear sampling
  76838. // Walk from left to center, combining pairs (symmetrically)
  76839. var linearSamplingWeights = [];
  76840. var linearSamplingOffsets = [];
  76841. var linearSamplingMap = [];
  76842. for (var i = 0; i <= centerIndex; i += 2) {
  76843. var j = Math.min(i + 1, Math.floor(centerIndex));
  76844. var singleCenterSample = i === j;
  76845. if (singleCenterSample) {
  76846. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76847. }
  76848. else {
  76849. var sharedCell = j === centerIndex;
  76850. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  76851. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  76852. if (offsetLinear === 0) {
  76853. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76854. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  76855. }
  76856. else {
  76857. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  76858. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  76859. }
  76860. }
  76861. }
  76862. for (var i = 0; i < linearSamplingMap.length; i++) {
  76863. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  76864. linearSamplingWeights[i] = linearSamplingMap[i].w;
  76865. }
  76866. // Replace with optimized
  76867. offsets = linearSamplingOffsets;
  76868. weights = linearSamplingWeights;
  76869. // Generate shaders
  76870. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  76871. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  76872. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  76873. var defines = "";
  76874. defines += this._staticDefines;
  76875. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  76876. if (this._staticDefines.indexOf("DOF") != -1) {
  76877. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  76878. varyingCount--;
  76879. }
  76880. for (var i = 0; i < varyingCount; i++) {
  76881. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  76882. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  76883. }
  76884. var depCount = 0;
  76885. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  76886. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  76887. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  76888. depCount++;
  76889. }
  76890. if (this.packedFloat) {
  76891. defines += "#define PACKEDFLOAT 1";
  76892. }
  76893. this.blockCompilation = false;
  76894. _super.prototype.updateEffect.call(this, defines, null, null, {
  76895. varyingCount: varyingCount,
  76896. depCount: depCount
  76897. }, onCompiled, onError);
  76898. };
  76899. /**
  76900. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  76901. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  76902. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  76903. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  76904. * The gaps between physical kernels are compensated for in the weighting of the samples
  76905. * @param idealKernel Ideal blur kernel.
  76906. * @return Nearest best kernel.
  76907. */
  76908. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  76909. var v = Math.round(idealKernel);
  76910. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  76911. var k = _a[_i];
  76912. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  76913. return Math.max(k, 3);
  76914. }
  76915. }
  76916. return Math.max(v, 3);
  76917. };
  76918. /**
  76919. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  76920. * @param x The point on the Gaussian distribution to sample.
  76921. * @return the value of the Gaussian function at x.
  76922. */
  76923. BlurPostProcess.prototype._gaussianWeight = function (x) {
  76924. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  76925. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  76926. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  76927. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  76928. // truncated at around 1.3% of peak strength.
  76929. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  76930. var sigma = (1 / 3);
  76931. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  76932. var exponent = -((x * x) / (2.0 * sigma * sigma));
  76933. var weight = (1.0 / denominator) * Math.exp(exponent);
  76934. return weight;
  76935. };
  76936. /**
  76937. * Generates a string that can be used as a floating point number in GLSL.
  76938. * @param x Value to print.
  76939. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  76940. * @return GLSL float string.
  76941. */
  76942. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  76943. if (decimalFigures === void 0) { decimalFigures = 8; }
  76944. return x.toFixed(decimalFigures).replace(/0+$/, '');
  76945. };
  76946. return BlurPostProcess;
  76947. }(BABYLON.PostProcess));
  76948. BABYLON.BlurPostProcess = BlurPostProcess;
  76949. })(BABYLON || (BABYLON = {}));
  76950. //# sourceMappingURL=babylon.blurPostProcess.js.map
  76951. var BABYLON;
  76952. (function (BABYLON) {
  76953. /**
  76954. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  76955. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  76956. * based on samples that have a large difference in distance than the center pixel.
  76957. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76958. */
  76959. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  76960. __extends(DepthOfFieldBlurPostProcess, _super);
  76961. /**
  76962. * Creates a new instance CircleOfConfusionPostProcess
  76963. * @param name The name of the effect.
  76964. * @param scene The scene the effect belongs to.
  76965. * @param direction The direction the blur should be applied.
  76966. * @param kernel The size of the kernel used to blur.
  76967. * @param options The required width/height ratio to downsize to before computing the render pass.
  76968. * @param camera The camera to apply the render pass to.
  76969. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  76970. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  76971. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76972. * @param engine The engine which the post process will be applied. (default: current engine)
  76973. * @param reusable If the post process can be reused on the same frame. (default: false)
  76974. * @param textureType Type of textures used when performing the post process. (default: 0)
  76975. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  76976. */
  76977. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  76978. if (imageToBlur === void 0) { imageToBlur = null; }
  76979. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76980. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76981. if (blockCompilation === void 0) { blockCompilation = false; }
  76982. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  76983. _this.direction = direction;
  76984. _this.onApplyObservable.add(function (effect) {
  76985. if (imageToBlur != null) {
  76986. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  76987. }
  76988. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  76989. if (scene.activeCamera) {
  76990. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  76991. }
  76992. });
  76993. return _this;
  76994. }
  76995. return DepthOfFieldBlurPostProcess;
  76996. }(BABYLON.BlurPostProcess));
  76997. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  76998. })(BABYLON || (BABYLON = {}));
  76999. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  77000. var BABYLON;
  77001. (function (BABYLON) {
  77002. /**
  77003. * Options to be set when merging outputs from the default pipeline.
  77004. */
  77005. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  77006. function DepthOfFieldMergePostProcessOptions() {
  77007. }
  77008. return DepthOfFieldMergePostProcessOptions;
  77009. }());
  77010. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  77011. /**
  77012. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77013. */
  77014. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  77015. __extends(DepthOfFieldMergePostProcess, _super);
  77016. /**
  77017. * Creates a new instance of DepthOfFieldMergePostProcess
  77018. * @param name The name of the effect.
  77019. * @param originalFromInput Post process which's input will be used for the merge.
  77020. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  77021. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  77022. * @param options The required width/height ratio to downsize to before computing the render pass.
  77023. * @param camera The camera to apply the render pass to.
  77024. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77025. * @param engine The engine which the post process will be applied. (default: current engine)
  77026. * @param reusable If the post process can be reused on the same frame. (default: false)
  77027. * @param textureType Type of textures used when performing the post process. (default: 0)
  77028. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  77029. */
  77030. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77031. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77032. if (blockCompilation === void 0) { blockCompilation = false; }
  77033. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77034. _this.blurSteps = blurSteps;
  77035. _this.onApplyObservable.add(function (effect) {
  77036. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77037. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77038. blurSteps.forEach(function (step, index) {
  77039. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  77040. });
  77041. });
  77042. if (!blockCompilation) {
  77043. _this.updateEffect();
  77044. }
  77045. return _this;
  77046. }
  77047. /**
  77048. * Updates the effect with the current post process compile time values and recompiles the shader.
  77049. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77050. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77051. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77052. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  77053. * @param onCompiled Called when the shader has been compiled.
  77054. * @param onError Called if there is an error when compiling a shader.
  77055. */
  77056. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77057. if (defines === void 0) { defines = null; }
  77058. if (uniforms === void 0) { uniforms = null; }
  77059. if (samplers === void 0) { samplers = null; }
  77060. if (!defines) {
  77061. defines = "";
  77062. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  77063. }
  77064. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  77065. };
  77066. return DepthOfFieldMergePostProcess;
  77067. }(BABYLON.PostProcess));
  77068. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  77069. })(BABYLON || (BABYLON = {}));
  77070. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  77071. var BABYLON;
  77072. (function (BABYLON) {
  77073. /**
  77074. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  77075. */
  77076. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  77077. __extends(CircleOfConfusionPostProcess, _super);
  77078. /**
  77079. * Creates a new instance CircleOfConfusionPostProcess
  77080. * @param name The name of the effect.
  77081. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  77082. * @param options The required width/height ratio to downsize to before computing the render pass.
  77083. * @param camera The camera to apply the render pass to.
  77084. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77085. * @param engine The engine which the post process will be applied. (default: current engine)
  77086. * @param reusable If the post process can be reused on the same frame. (default: false)
  77087. * @param textureType Type of textures used when performing the post process. (default: 0)
  77088. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  77089. */
  77090. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77091. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77092. if (blockCompilation === void 0) { blockCompilation = false; }
  77093. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77094. /**
  77095. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  77096. */
  77097. _this.lensSize = 50;
  77098. /**
  77099. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77100. */
  77101. _this.fStop = 1.4;
  77102. /**
  77103. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77104. */
  77105. _this.focusDistance = 2000;
  77106. /**
  77107. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  77108. */
  77109. _this.focalLength = 50;
  77110. _this._depthTexture = null;
  77111. _this._depthTexture = depthTexture;
  77112. _this.onApplyObservable.add(function (effect) {
  77113. if (!_this._depthTexture) {
  77114. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  77115. return;
  77116. }
  77117. effect.setTexture("depthSampler", _this._depthTexture);
  77118. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  77119. var aperture = _this.lensSize / _this.fStop;
  77120. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  77121. effect.setFloat('focusDistance', _this.focusDistance);
  77122. effect.setFloat('cocPrecalculation', cocPrecalculation);
  77123. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  77124. });
  77125. return _this;
  77126. }
  77127. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  77128. /**
  77129. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  77130. */
  77131. set: function (value) {
  77132. this._depthTexture = value;
  77133. },
  77134. enumerable: true,
  77135. configurable: true
  77136. });
  77137. return CircleOfConfusionPostProcess;
  77138. }(BABYLON.PostProcess));
  77139. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  77140. })(BABYLON || (BABYLON = {}));
  77141. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  77142. var BABYLON;
  77143. (function (BABYLON) {
  77144. /**
  77145. * Specifies the level of max blur that should be applied when using the depth of field effect
  77146. */
  77147. var DepthOfFieldEffectBlurLevel;
  77148. (function (DepthOfFieldEffectBlurLevel) {
  77149. /**
  77150. * Subtle blur
  77151. */
  77152. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  77153. /**
  77154. * Medium blur
  77155. */
  77156. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  77157. /**
  77158. * Large blur
  77159. */
  77160. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  77161. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  77162. ;
  77163. /**
  77164. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  77165. */
  77166. var DepthOfFieldEffect = /** @class */ (function (_super) {
  77167. __extends(DepthOfFieldEffect, _super);
  77168. /**
  77169. * Creates a new instance DepthOfFieldEffect
  77170. * @param scene The scene the effect belongs to.
  77171. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  77172. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77173. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  77174. */
  77175. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  77176. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  77177. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77178. if (blockCompilation === void 0) { blockCompilation = false; }
  77179. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  77180. return _this._effects;
  77181. }, true) || this;
  77182. /**
  77183. * Internal post processes in depth of field effect
  77184. */
  77185. _this._effects = [];
  77186. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  77187. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77188. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  77189. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  77190. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77191. _this._depthOfFieldBlurY = [];
  77192. _this._depthOfFieldBlurX = [];
  77193. var blurCount = 1;
  77194. var kernelSize = 15;
  77195. switch (blurLevel) {
  77196. case DepthOfFieldEffectBlurLevel.High: {
  77197. blurCount = 3;
  77198. kernelSize = 51;
  77199. break;
  77200. }
  77201. case DepthOfFieldEffectBlurLevel.Medium: {
  77202. blurCount = 2;
  77203. kernelSize = 31;
  77204. break;
  77205. }
  77206. default: {
  77207. kernelSize = 15;
  77208. blurCount = 1;
  77209. break;
  77210. }
  77211. }
  77212. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  77213. var ratio = 1.0;
  77214. for (var i = 0; i < blurCount; i++) {
  77215. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77216. blurY.autoClear = false;
  77217. ratio = 0.75 / Math.pow(2, i);
  77218. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77219. blurX.autoClear = false;
  77220. _this._depthOfFieldBlurY.push(blurY);
  77221. _this._depthOfFieldBlurX.push(blurX);
  77222. }
  77223. // Set all post processes on the effect.
  77224. _this._effects = [_this._circleOfConfusion];
  77225. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  77226. _this._effects.push(_this._depthOfFieldBlurY[i]);
  77227. _this._effects.push(_this._depthOfFieldBlurX[i]);
  77228. }
  77229. // Merge blurred images with original image based on circleOfConfusion
  77230. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77231. _this._dofMerge.autoClear = false;
  77232. _this._effects.push(_this._dofMerge);
  77233. return _this;
  77234. }
  77235. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  77236. get: function () {
  77237. return this._circleOfConfusion.focalLength;
  77238. },
  77239. /**
  77240. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  77241. */
  77242. set: function (value) {
  77243. this._circleOfConfusion.focalLength = value;
  77244. },
  77245. enumerable: true,
  77246. configurable: true
  77247. });
  77248. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  77249. get: function () {
  77250. return this._circleOfConfusion.fStop;
  77251. },
  77252. /**
  77253. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77254. */
  77255. set: function (value) {
  77256. this._circleOfConfusion.fStop = value;
  77257. },
  77258. enumerable: true,
  77259. configurable: true
  77260. });
  77261. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  77262. get: function () {
  77263. return this._circleOfConfusion.focusDistance;
  77264. },
  77265. /**
  77266. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77267. */
  77268. set: function (value) {
  77269. this._circleOfConfusion.focusDistance = value;
  77270. },
  77271. enumerable: true,
  77272. configurable: true
  77273. });
  77274. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  77275. get: function () {
  77276. return this._circleOfConfusion.lensSize;
  77277. },
  77278. /**
  77279. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  77280. */
  77281. set: function (value) {
  77282. this._circleOfConfusion.lensSize = value;
  77283. },
  77284. enumerable: true,
  77285. configurable: true
  77286. });
  77287. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  77288. /**
  77289. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  77290. */
  77291. set: function (value) {
  77292. this._circleOfConfusion.depthTexture = value;
  77293. },
  77294. enumerable: true,
  77295. configurable: true
  77296. });
  77297. /**
  77298. * Disposes each of the internal effects for a given camera.
  77299. * @param camera The camera to dispose the effect on.
  77300. */
  77301. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  77302. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77303. this._effects[effectIndex].dispose(camera);
  77304. }
  77305. };
  77306. /**
  77307. * Internal
  77308. */
  77309. DepthOfFieldEffect.prototype._updateEffects = function () {
  77310. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77311. this._effects[effectIndex].updateEffect();
  77312. }
  77313. };
  77314. /**
  77315. * Internal
  77316. * @returns if all the contained post processes are ready.
  77317. */
  77318. DepthOfFieldEffect.prototype._isReady = function () {
  77319. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77320. if (!this._effects[effectIndex].isReady()) {
  77321. return false;
  77322. }
  77323. }
  77324. return true;
  77325. };
  77326. return DepthOfFieldEffect;
  77327. }(BABYLON.PostProcessRenderEffect));
  77328. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  77329. })(BABYLON || (BABYLON = {}));
  77330. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  77331. var BABYLON;
  77332. (function (BABYLON) {
  77333. /**
  77334. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77335. */
  77336. var BloomMergePostProcess = /** @class */ (function (_super) {
  77337. __extends(BloomMergePostProcess, _super);
  77338. /**
  77339. * Creates a new instance of @see BloomMergePostProcess
  77340. * @param name The name of the effect.
  77341. * @param originalFromInput Post process which's input will be used for the merge.
  77342. * @param blurred Blurred highlights post process which's output will be used.
  77343. * @param weight Weight of the bloom to be added to the original input.
  77344. * @param options The required width/height ratio to downsize to before computing the render pass.
  77345. * @param camera The camera to apply the render pass to.
  77346. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77347. * @param engine The engine which the post process will be applied. (default: current engine)
  77348. * @param reusable If the post process can be reused on the same frame. (default: false)
  77349. * @param textureType Type of textures used when performing the post process. (default: 0)
  77350. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  77351. */
  77352. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77353. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77354. if (blockCompilation === void 0) { blockCompilation = false; }
  77355. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77356. _this.weight = weight;
  77357. _this.onApplyObservable.add(function (effect) {
  77358. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77359. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  77360. effect.setFloat("bloomWeight", _this.weight);
  77361. });
  77362. if (!blockCompilation) {
  77363. _this.updateEffect();
  77364. }
  77365. return _this;
  77366. }
  77367. return BloomMergePostProcess;
  77368. }(BABYLON.PostProcess));
  77369. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  77370. })(BABYLON || (BABYLON = {}));
  77371. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  77372. var BABYLON;
  77373. (function (BABYLON) {
  77374. /**
  77375. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  77376. */
  77377. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  77378. __extends(ExtractHighlightsPostProcess, _super);
  77379. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77380. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77381. if (blockCompilation === void 0) { blockCompilation = false; }
  77382. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77383. /**
  77384. * The luminance threshold, pixels below this value will be set to black.
  77385. */
  77386. _this.threshold = 0.9;
  77387. /**
  77388. * Internal
  77389. */
  77390. _this._exposure = 1;
  77391. /**
  77392. * Post process which has the input texture to be used when performing highlight extraction
  77393. */
  77394. _this._inputPostProcess = null;
  77395. _this.onApplyObservable.add(function (effect) {
  77396. if (_this._inputPostProcess) {
  77397. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  77398. }
  77399. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  77400. effect.setFloat('exposure', _this._exposure);
  77401. });
  77402. return _this;
  77403. }
  77404. return ExtractHighlightsPostProcess;
  77405. }(BABYLON.PostProcess));
  77406. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  77407. })(BABYLON || (BABYLON = {}));
  77408. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  77409. var BABYLON;
  77410. (function (BABYLON) {
  77411. /**
  77412. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  77413. */
  77414. var BloomEffect = /** @class */ (function (_super) {
  77415. __extends(BloomEffect, _super);
  77416. /**
  77417. * Creates a new instance of @see BloomEffect
  77418. * @param scene The scene the effect belongs to.
  77419. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  77420. * @param bloomKernel The size of the kernel to be used when applying the blur.
  77421. * @param bloomWeight The the strength of bloom.
  77422. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77423. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  77424. */
  77425. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  77426. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77427. if (blockCompilation === void 0) { blockCompilation = false; }
  77428. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  77429. return _this._effects;
  77430. }, true) || this;
  77431. _this.bloomScale = bloomScale;
  77432. /**
  77433. * Internal
  77434. */
  77435. _this._effects = [];
  77436. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77437. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  77438. _this._blurX.alwaysForcePOT = true;
  77439. _this._blurX.autoClear = false;
  77440. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  77441. _this._blurY.alwaysForcePOT = true;
  77442. _this._blurY.autoClear = false;
  77443. _this.kernel = bloomKernel;
  77444. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  77445. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77446. _this._merge.autoClear = false;
  77447. _this._effects.push(_this._merge);
  77448. return _this;
  77449. }
  77450. Object.defineProperty(BloomEffect.prototype, "threshold", {
  77451. /**
  77452. * The luminance threshold to find bright areas of the image to bloom.
  77453. */
  77454. get: function () {
  77455. return this._downscale.threshold;
  77456. },
  77457. set: function (value) {
  77458. this._downscale.threshold = value;
  77459. },
  77460. enumerable: true,
  77461. configurable: true
  77462. });
  77463. Object.defineProperty(BloomEffect.prototype, "weight", {
  77464. /**
  77465. * The strength of the bloom.
  77466. */
  77467. get: function () {
  77468. return this._merge.weight;
  77469. },
  77470. set: function (value) {
  77471. this._merge.weight = value;
  77472. },
  77473. enumerable: true,
  77474. configurable: true
  77475. });
  77476. Object.defineProperty(BloomEffect.prototype, "kernel", {
  77477. /**
  77478. * Specifies the size of the bloom blur kernel, relative to the final output size
  77479. */
  77480. get: function () {
  77481. return this._blurX.kernel / this.bloomScale;
  77482. },
  77483. set: function (value) {
  77484. this._blurX.kernel = value * this.bloomScale;
  77485. this._blurY.kernel = value * this.bloomScale;
  77486. },
  77487. enumerable: true,
  77488. configurable: true
  77489. });
  77490. /**
  77491. * Disposes each of the internal effects for a given camera.
  77492. * @param camera The camera to dispose the effect on.
  77493. */
  77494. BloomEffect.prototype.disposeEffects = function (camera) {
  77495. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77496. this._effects[effectIndex].dispose(camera);
  77497. }
  77498. };
  77499. /**
  77500. * Internal
  77501. */
  77502. BloomEffect.prototype._updateEffects = function () {
  77503. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77504. this._effects[effectIndex].updateEffect();
  77505. }
  77506. };
  77507. /**
  77508. * Internal
  77509. * @returns if all the contained post processes are ready.
  77510. */
  77511. BloomEffect.prototype._isReady = function () {
  77512. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77513. if (!this._effects[effectIndex].isReady()) {
  77514. return false;
  77515. }
  77516. }
  77517. return true;
  77518. };
  77519. return BloomEffect;
  77520. }(BABYLON.PostProcessRenderEffect));
  77521. BABYLON.BloomEffect = BloomEffect;
  77522. })(BABYLON || (BABYLON = {}));
  77523. //# sourceMappingURL=babylon.bloomEffect.js.map
  77524. var BABYLON;
  77525. (function (BABYLON) {
  77526. /**
  77527. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  77528. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  77529. */
  77530. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  77531. __extends(DefaultRenderingPipeline, _super);
  77532. /**
  77533. * @constructor
  77534. * @param {string} name - The rendering pipeline name (default: "")
  77535. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  77536. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  77537. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  77538. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  77539. */
  77540. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  77541. if (name === void 0) { name = ""; }
  77542. if (hdr === void 0) { hdr = true; }
  77543. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77544. if (automaticBuild === void 0) { automaticBuild = true; }
  77545. var _this = _super.call(this, scene.getEngine(), name) || this;
  77546. _this._camerasToBeAttached = [];
  77547. /**
  77548. * ID of the sharpen post process,
  77549. */
  77550. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  77551. /**
  77552. * ID of the image processing post process;
  77553. */
  77554. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  77555. /**
  77556. * ID of the Fast Approximate Anti-Aliasing post process;
  77557. */
  77558. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  77559. /**
  77560. * ID of the chromatic aberration post process,
  77561. */
  77562. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  77563. /**
  77564. * ID of the grain post process
  77565. */
  77566. _this.GrainPostProcessId = "GrainPostProcessEffect";
  77567. /**
  77568. * Glow post process which adds a glow to emmisive areas of the image
  77569. */
  77570. _this._glowLayer = null;
  77571. /**
  77572. * Animations which can be used to tweak settings over a period of time
  77573. */
  77574. _this.animations = [];
  77575. _this._imageProcessingConfigurationObserver = null;
  77576. // Values
  77577. _this._sharpenEnabled = false;
  77578. _this._bloomEnabled = false;
  77579. _this._depthOfFieldEnabled = false;
  77580. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  77581. _this._fxaaEnabled = false;
  77582. _this._imageProcessingEnabled = true;
  77583. _this._bloomScale = 0.5;
  77584. _this._chromaticAberrationEnabled = false;
  77585. _this._grainEnabled = false;
  77586. _this._buildAllowed = true;
  77587. _this._resizeObserver = null;
  77588. _this._hardwareScaleLevel = 1.0;
  77589. _this._bloomKernel = 64;
  77590. /**
  77591. * Specifies the weight of the bloom in the final rendering
  77592. */
  77593. _this._bloomWeight = 0.15;
  77594. /**
  77595. * Specifies the luma threshold for the area that will be blurred by the bloom
  77596. */
  77597. _this._bloomThreshold = 0.9;
  77598. _this._samples = 1;
  77599. _this._hasCleared = false;
  77600. _this._prevPostProcess = null;
  77601. _this._prevPrevPostProcess = null;
  77602. _this._cameras = cameras || scene.cameras;
  77603. _this._camerasToBeAttached = _this._cameras.slice();
  77604. _this._buildAllowed = automaticBuild;
  77605. // Initialize
  77606. _this._scene = scene;
  77607. var caps = _this._scene.getEngine().getCaps();
  77608. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  77609. // Misc
  77610. if (_this._hdr) {
  77611. if (caps.textureHalfFloatRender) {
  77612. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77613. }
  77614. else if (caps.textureFloatRender) {
  77615. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77616. }
  77617. }
  77618. else {
  77619. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77620. }
  77621. // Attach
  77622. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77623. var engine = _this._scene.getEngine();
  77624. // Create post processes before hand so they can be modified before enabled.
  77625. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  77626. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77627. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  77628. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  77629. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  77630. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77631. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  77632. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77633. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  77634. _this._resizeObserver = engine.onResizeObservable.add(function () {
  77635. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  77636. _this.bloomKernel = _this.bloomKernel;
  77637. });
  77638. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  77639. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  77640. });
  77641. _this._buildPipeline();
  77642. return _this;
  77643. }
  77644. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  77645. get: function () {
  77646. return this._sharpenEnabled;
  77647. },
  77648. /**
  77649. * Enable or disable the sharpen process from the pipeline
  77650. */
  77651. set: function (enabled) {
  77652. if (this._sharpenEnabled === enabled) {
  77653. return;
  77654. }
  77655. this._sharpenEnabled = enabled;
  77656. this._buildPipeline();
  77657. },
  77658. enumerable: true,
  77659. configurable: true
  77660. });
  77661. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  77662. /**
  77663. * Specifies the size of the bloom blur kernel, relative to the final output size
  77664. */
  77665. get: function () {
  77666. return this._bloomKernel;
  77667. },
  77668. set: function (value) {
  77669. this._bloomKernel = value;
  77670. this.bloom.kernel = value / this._hardwareScaleLevel;
  77671. },
  77672. enumerable: true,
  77673. configurable: true
  77674. });
  77675. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  77676. get: function () {
  77677. return this._bloomWeight;
  77678. },
  77679. /**
  77680. * The strength of the bloom.
  77681. */
  77682. set: function (value) {
  77683. if (this._bloomWeight === value) {
  77684. return;
  77685. }
  77686. this.bloom.weight = value;
  77687. this._bloomWeight = value;
  77688. },
  77689. enumerable: true,
  77690. configurable: true
  77691. });
  77692. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  77693. get: function () {
  77694. return this._bloomThreshold;
  77695. },
  77696. /**
  77697. * The strength of the bloom.
  77698. */
  77699. set: function (value) {
  77700. if (this._bloomThreshold === value) {
  77701. return;
  77702. }
  77703. this.bloom.threshold = value;
  77704. this._bloomThreshold = value;
  77705. },
  77706. enumerable: true,
  77707. configurable: true
  77708. });
  77709. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  77710. get: function () {
  77711. return this._bloomScale;
  77712. },
  77713. /**
  77714. * The scale of the bloom, lower value will provide better performance.
  77715. */
  77716. set: function (value) {
  77717. if (this._bloomScale === value) {
  77718. return;
  77719. }
  77720. this._bloomScale = value;
  77721. // recreate bloom and dispose old as this setting is not dynamic
  77722. this._rebuildBloom();
  77723. this._buildPipeline();
  77724. },
  77725. enumerable: true,
  77726. configurable: true
  77727. });
  77728. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  77729. get: function () {
  77730. return this._bloomEnabled;
  77731. },
  77732. /**
  77733. * Enable or disable the bloom from the pipeline
  77734. */
  77735. set: function (enabled) {
  77736. if (this._bloomEnabled === enabled) {
  77737. return;
  77738. }
  77739. this._bloomEnabled = enabled;
  77740. this._buildPipeline();
  77741. },
  77742. enumerable: true,
  77743. configurable: true
  77744. });
  77745. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  77746. // recreate bloom and dispose old as this setting is not dynamic
  77747. var oldBloom = this.bloom;
  77748. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  77749. this.bloom.threshold = oldBloom.threshold;
  77750. for (var i = 0; i < this._cameras.length; i++) {
  77751. oldBloom.disposeEffects(this._cameras[i]);
  77752. }
  77753. };
  77754. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  77755. /**
  77756. * If the depth of field is enabled.
  77757. */
  77758. get: function () {
  77759. return this._depthOfFieldEnabled;
  77760. },
  77761. set: function (enabled) {
  77762. if (this._depthOfFieldEnabled === enabled) {
  77763. return;
  77764. }
  77765. this._depthOfFieldEnabled = enabled;
  77766. this._buildPipeline();
  77767. },
  77768. enumerable: true,
  77769. configurable: true
  77770. });
  77771. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  77772. /**
  77773. * Blur level of the depth of field effect. (Higher blur will effect performance)
  77774. */
  77775. get: function () {
  77776. return this._depthOfFieldBlurLevel;
  77777. },
  77778. set: function (value) {
  77779. if (this._depthOfFieldBlurLevel === value) {
  77780. return;
  77781. }
  77782. this._depthOfFieldBlurLevel = value;
  77783. // recreate dof and dispose old as this setting is not dynamic
  77784. var oldDof = this.depthOfField;
  77785. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  77786. this.depthOfField.focalLength = oldDof.focalLength;
  77787. this.depthOfField.focusDistance = oldDof.focusDistance;
  77788. this.depthOfField.fStop = oldDof.fStop;
  77789. this.depthOfField.lensSize = oldDof.lensSize;
  77790. for (var i = 0; i < this._cameras.length; i++) {
  77791. oldDof.disposeEffects(this._cameras[i]);
  77792. }
  77793. this._buildPipeline();
  77794. },
  77795. enumerable: true,
  77796. configurable: true
  77797. });
  77798. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  77799. get: function () {
  77800. return this._fxaaEnabled;
  77801. },
  77802. /**
  77803. * If the anti aliasing is enabled.
  77804. */
  77805. set: function (enabled) {
  77806. if (this._fxaaEnabled === enabled) {
  77807. return;
  77808. }
  77809. this._fxaaEnabled = enabled;
  77810. this._buildPipeline();
  77811. },
  77812. enumerable: true,
  77813. configurable: true
  77814. });
  77815. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  77816. get: function () {
  77817. return this._samples;
  77818. },
  77819. /**
  77820. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  77821. */
  77822. set: function (sampleCount) {
  77823. if (this._samples === sampleCount) {
  77824. return;
  77825. }
  77826. this._samples = sampleCount;
  77827. this._buildPipeline();
  77828. },
  77829. enumerable: true,
  77830. configurable: true
  77831. });
  77832. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  77833. get: function () {
  77834. return this._imageProcessingEnabled;
  77835. },
  77836. /**
  77837. * If image processing is enabled.
  77838. */
  77839. set: function (enabled) {
  77840. if (this._imageProcessingEnabled === enabled) {
  77841. return;
  77842. }
  77843. this._imageProcessingEnabled = enabled;
  77844. this._buildPipeline();
  77845. },
  77846. enumerable: true,
  77847. configurable: true
  77848. });
  77849. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  77850. get: function () {
  77851. return this._glowLayer == null;
  77852. },
  77853. /**
  77854. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  77855. */
  77856. set: function (enabled) {
  77857. if (enabled && !this._glowLayer) {
  77858. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  77859. }
  77860. else if (!enabled && this._glowLayer) {
  77861. this._glowLayer.dispose();
  77862. this._glowLayer = null;
  77863. }
  77864. },
  77865. enumerable: true,
  77866. configurable: true
  77867. });
  77868. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  77869. get: function () {
  77870. return this._chromaticAberrationEnabled;
  77871. },
  77872. /**
  77873. * Enable or disable the chromaticAberration process from the pipeline
  77874. */
  77875. set: function (enabled) {
  77876. if (this._chromaticAberrationEnabled === enabled) {
  77877. return;
  77878. }
  77879. this._chromaticAberrationEnabled = enabled;
  77880. this._buildPipeline();
  77881. },
  77882. enumerable: true,
  77883. configurable: true
  77884. });
  77885. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  77886. get: function () {
  77887. return this._grainEnabled;
  77888. },
  77889. /**
  77890. * Enable or disable the grain process from the pipeline
  77891. */
  77892. set: function (enabled) {
  77893. if (this._grainEnabled === enabled) {
  77894. return;
  77895. }
  77896. this._grainEnabled = enabled;
  77897. this._buildPipeline();
  77898. },
  77899. enumerable: true,
  77900. configurable: true
  77901. });
  77902. /**
  77903. * Force the compilation of the entire pipeline.
  77904. */
  77905. DefaultRenderingPipeline.prototype.prepare = function () {
  77906. var previousState = this._buildAllowed;
  77907. this._buildAllowed = true;
  77908. this._buildPipeline();
  77909. this._buildAllowed = previousState;
  77910. };
  77911. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  77912. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  77913. if (this._hasCleared) {
  77914. postProcess.autoClear = false;
  77915. }
  77916. else {
  77917. postProcess.autoClear = true;
  77918. this._scene.autoClear = false;
  77919. this._hasCleared = true;
  77920. }
  77921. if (!skipTextureSharing) {
  77922. if (this._prevPrevPostProcess) {
  77923. postProcess.shareOutputWith(this._prevPrevPostProcess);
  77924. }
  77925. else {
  77926. postProcess.useOwnOutput();
  77927. }
  77928. if (this._prevPostProcess) {
  77929. this._prevPrevPostProcess = this._prevPostProcess;
  77930. }
  77931. this._prevPostProcess = postProcess;
  77932. }
  77933. };
  77934. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  77935. var _this = this;
  77936. if (!this._buildAllowed) {
  77937. return;
  77938. }
  77939. this._scene.autoClear = true;
  77940. var engine = this._scene.getEngine();
  77941. this._disposePostProcesses();
  77942. if (this._cameras !== null) {
  77943. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77944. // get back cameras to be used to reattach pipeline
  77945. this._cameras = this._camerasToBeAttached.slice();
  77946. }
  77947. this._reset();
  77948. this._prevPostProcess = null;
  77949. this._prevPrevPostProcess = null;
  77950. this._hasCleared = false;
  77951. if (this.depthOfFieldEnabled) {
  77952. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  77953. this.depthOfField.depthTexture = depthTexture;
  77954. if (!this.depthOfField._isReady()) {
  77955. this.depthOfField._updateEffects();
  77956. }
  77957. this.addEffect(this.depthOfField);
  77958. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  77959. }
  77960. if (this.bloomEnabled) {
  77961. if (!this.bloom._isReady()) {
  77962. this.bloom._updateEffects();
  77963. }
  77964. this.addEffect(this.bloom);
  77965. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  77966. }
  77967. if (this._imageProcessingEnabled) {
  77968. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  77969. if (this._hdr) {
  77970. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  77971. this._setAutoClearAndTextureSharing(this.imageProcessing);
  77972. }
  77973. else {
  77974. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  77975. }
  77976. }
  77977. if (this.sharpenEnabled) {
  77978. if (!this.sharpen.isReady()) {
  77979. this.sharpen.updateEffect();
  77980. }
  77981. this.addEffect(this._sharpenEffect);
  77982. this._setAutoClearAndTextureSharing(this.sharpen);
  77983. }
  77984. if (this.grainEnabled) {
  77985. if (!this.grain.isReady()) {
  77986. this.grain.updateEffect();
  77987. }
  77988. this.addEffect(this._grainEffect);
  77989. this._setAutoClearAndTextureSharing(this.grain);
  77990. }
  77991. if (this.chromaticAberrationEnabled) {
  77992. if (!this.chromaticAberration.isReady()) {
  77993. this.chromaticAberration.updateEffect();
  77994. }
  77995. this.addEffect(this._chromaticAberrationEffect);
  77996. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  77997. }
  77998. if (this.fxaaEnabled) {
  77999. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78000. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  78001. this._setAutoClearAndTextureSharing(this.fxaa, true);
  78002. }
  78003. if (this._cameras !== null) {
  78004. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78005. }
  78006. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  78007. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  78008. }
  78009. };
  78010. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  78011. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  78012. for (var i = 0; i < this._cameras.length; i++) {
  78013. var camera = this._cameras[i];
  78014. if (this.imageProcessing) {
  78015. this.imageProcessing.dispose(camera);
  78016. }
  78017. if (this.fxaa) {
  78018. this.fxaa.dispose(camera);
  78019. }
  78020. // These are created in the constructor and should not be disposed on every pipeline change
  78021. if (disposeNonRecreated) {
  78022. if (this.sharpen) {
  78023. this.sharpen.dispose(camera);
  78024. }
  78025. if (this.depthOfField) {
  78026. this.depthOfField.disposeEffects(camera);
  78027. }
  78028. if (this.bloom) {
  78029. this.bloom.disposeEffects(camera);
  78030. }
  78031. if (this.chromaticAberration) {
  78032. this.chromaticAberration.dispose(camera);
  78033. }
  78034. if (this.grain) {
  78035. this.grain.dispose(camera);
  78036. }
  78037. if (this._glowLayer) {
  78038. this._glowLayer.dispose();
  78039. }
  78040. }
  78041. }
  78042. this.imageProcessing = null;
  78043. this.fxaa = null;
  78044. if (disposeNonRecreated) {
  78045. this.sharpen = null;
  78046. this._sharpenEffect = null;
  78047. this.depthOfField = null;
  78048. this.bloom = null;
  78049. this.chromaticAberration = null;
  78050. this._chromaticAberrationEffect = null;
  78051. this.grain = null;
  78052. this._grainEffect = null;
  78053. this._glowLayer = null;
  78054. }
  78055. };
  78056. /**
  78057. * Adds a camera to the pipeline
  78058. * @param camera the camera to be added
  78059. */
  78060. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  78061. this._camerasToBeAttached.push(camera);
  78062. this._buildPipeline();
  78063. };
  78064. /**
  78065. * Removes a camera from the pipeline
  78066. * @param camera the camera to remove
  78067. */
  78068. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  78069. var index = this._camerasToBeAttached.indexOf(camera);
  78070. this._camerasToBeAttached.splice(index, 1);
  78071. this._buildPipeline();
  78072. };
  78073. /**
  78074. * Dispose of the pipeline and stop all post processes
  78075. */
  78076. DefaultRenderingPipeline.prototype.dispose = function () {
  78077. this._disposePostProcesses(true);
  78078. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78079. this._scene.autoClear = true;
  78080. if (this._resizeObserver) {
  78081. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  78082. this._resizeObserver = null;
  78083. }
  78084. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  78085. _super.prototype.dispose.call(this);
  78086. };
  78087. /**
  78088. * Serialize the rendering pipeline (Used when exporting)
  78089. * @returns the serialized object
  78090. */
  78091. DefaultRenderingPipeline.prototype.serialize = function () {
  78092. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78093. serializationObject.customType = "DefaultRenderingPipeline";
  78094. return serializationObject;
  78095. };
  78096. /**
  78097. * Parse the serialized pipeline
  78098. * @param source Source pipeline.
  78099. * @param scene The scene to load the pipeline to.
  78100. * @param rootUrl The URL of the serialized pipeline.
  78101. * @returns An instantiated pipeline from the serialized object.
  78102. */
  78103. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78104. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  78105. };
  78106. __decorate([
  78107. BABYLON.serialize()
  78108. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  78109. __decorate([
  78110. BABYLON.serialize()
  78111. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  78112. __decorate([
  78113. BABYLON.serialize()
  78114. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  78115. __decorate([
  78116. BABYLON.serialize()
  78117. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  78118. __decorate([
  78119. BABYLON.serialize()
  78120. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  78121. __decorate([
  78122. BABYLON.serialize()
  78123. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  78124. __decorate([
  78125. BABYLON.serialize()
  78126. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  78127. __decorate([
  78128. BABYLON.serialize()
  78129. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  78130. __decorate([
  78131. BABYLON.serialize()
  78132. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  78133. __decorate([
  78134. BABYLON.serialize()
  78135. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  78136. __decorate([
  78137. BABYLON.serialize()
  78138. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  78139. __decorate([
  78140. BABYLON.serialize()
  78141. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  78142. __decorate([
  78143. BABYLON.serialize()
  78144. ], DefaultRenderingPipeline.prototype, "samples", null);
  78145. __decorate([
  78146. BABYLON.serialize()
  78147. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  78148. __decorate([
  78149. BABYLON.serialize()
  78150. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  78151. __decorate([
  78152. BABYLON.serialize()
  78153. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  78154. __decorate([
  78155. BABYLON.serialize()
  78156. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  78157. return DefaultRenderingPipeline;
  78158. }(BABYLON.PostProcessRenderPipeline));
  78159. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  78160. })(BABYLON || (BABYLON = {}));
  78161. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  78162. var BABYLON;
  78163. (function (BABYLON) {
  78164. /**
  78165. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78166. */
  78167. var GeometryBufferRenderer = /** @class */ (function () {
  78168. /**
  78169. * Creates a new G Buffer for the scene
  78170. * @param scene The scene the buffer belongs to
  78171. * @param ratio How big is the buffer related to the main canvas.
  78172. */
  78173. function GeometryBufferRenderer(scene, ratio) {
  78174. if (ratio === void 0) { ratio = 1; }
  78175. this._enablePosition = false;
  78176. this._scene = scene;
  78177. this._ratio = ratio;
  78178. // Render target
  78179. this._createRenderTargets();
  78180. }
  78181. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78182. /**
  78183. * Set the render list (meshes to be rendered) used in the G buffer.
  78184. */
  78185. set: function (meshes) {
  78186. this._multiRenderTarget.renderList = meshes;
  78187. },
  78188. enumerable: true,
  78189. configurable: true
  78190. });
  78191. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78192. /**
  78193. * Gets wether or not G buffer are supported by the running hardware.
  78194. * This requires draw buffer supports
  78195. */
  78196. get: function () {
  78197. return this._multiRenderTarget.isSupported;
  78198. },
  78199. enumerable: true,
  78200. configurable: true
  78201. });
  78202. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78203. /**
  78204. * Gets wether or not position are enabled for the G buffer.
  78205. */
  78206. get: function () {
  78207. return this._enablePosition;
  78208. },
  78209. /**
  78210. * Sets wether or not position are enabled for the G buffer.
  78211. */
  78212. set: function (enable) {
  78213. this._enablePosition = enable;
  78214. this.dispose();
  78215. this._createRenderTargets();
  78216. },
  78217. enumerable: true,
  78218. configurable: true
  78219. });
  78220. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78221. /**
  78222. * Gets the scene associated with the buffer.
  78223. */
  78224. get: function () {
  78225. return this._scene;
  78226. },
  78227. enumerable: true,
  78228. configurable: true
  78229. });
  78230. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78231. /**
  78232. * Gets the ratio used by the buffer during its creation.
  78233. * How big is the buffer related to the main canvas.
  78234. */
  78235. get: function () {
  78236. return this._ratio;
  78237. },
  78238. enumerable: true,
  78239. configurable: true
  78240. });
  78241. /**
  78242. * Checks wether everything is ready to render a submesh to the G buffer.
  78243. * @param subMesh the submesh to check readiness for
  78244. * @param useInstances is the mesh drawn using instance or not
  78245. * @returns true if ready otherwise false
  78246. */
  78247. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78248. var material = subMesh.getMaterial();
  78249. if (material && material.disableDepthWrite) {
  78250. return false;
  78251. }
  78252. var defines = [];
  78253. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78254. var mesh = subMesh.getMesh();
  78255. // Alpha test
  78256. if (material && material.needAlphaTesting()) {
  78257. defines.push("#define ALPHATEST");
  78258. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78259. attribs.push(BABYLON.VertexBuffer.UVKind);
  78260. defines.push("#define UV1");
  78261. }
  78262. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78263. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78264. defines.push("#define UV2");
  78265. }
  78266. }
  78267. // Buffers
  78268. if (this._enablePosition) {
  78269. defines.push("#define POSITION");
  78270. }
  78271. // Bones
  78272. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78273. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78274. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78275. if (mesh.numBoneInfluencers > 4) {
  78276. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78277. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78278. }
  78279. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78280. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78281. }
  78282. else {
  78283. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78284. }
  78285. // Instances
  78286. if (useInstances) {
  78287. defines.push("#define INSTANCES");
  78288. attribs.push("world0");
  78289. attribs.push("world1");
  78290. attribs.push("world2");
  78291. attribs.push("world3");
  78292. }
  78293. // Get correct effect
  78294. var join = defines.join("\n");
  78295. if (this._cachedDefines !== join) {
  78296. this._cachedDefines = join;
  78297. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78298. }
  78299. return this._effect.isReady();
  78300. };
  78301. /**
  78302. * Gets the current underlying G Buffer.
  78303. * @returns the buffer
  78304. */
  78305. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78306. return this._multiRenderTarget;
  78307. };
  78308. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78309. /**
  78310. * Gets the number of samples used to render the buffer (anti aliasing).
  78311. */
  78312. get: function () {
  78313. return this._multiRenderTarget.samples;
  78314. },
  78315. /**
  78316. * Sets the number of samples used to render the buffer (anti aliasing).
  78317. */
  78318. set: function (value) {
  78319. this._multiRenderTarget.samples = value;
  78320. },
  78321. enumerable: true,
  78322. configurable: true
  78323. });
  78324. /**
  78325. * Disposes the renderer and frees up associated resources.
  78326. */
  78327. GeometryBufferRenderer.prototype.dispose = function () {
  78328. this.getGBuffer().dispose();
  78329. };
  78330. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78331. var _this = this;
  78332. var engine = this._scene.getEngine();
  78333. var count = this._enablePosition ? 3 : 2;
  78334. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  78335. if (!this.isSupported) {
  78336. return;
  78337. }
  78338. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78339. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78340. this._multiRenderTarget.refreshRate = 1;
  78341. this._multiRenderTarget.renderParticles = false;
  78342. this._multiRenderTarget.renderList = null;
  78343. // set default depth value to 1.0 (far away)
  78344. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78345. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78346. });
  78347. // Custom render function
  78348. var renderSubMesh = function (subMesh) {
  78349. var mesh = subMesh.getRenderingMesh();
  78350. var scene = _this._scene;
  78351. var engine = scene.getEngine();
  78352. var material = subMesh.getMaterial();
  78353. if (!material) {
  78354. return;
  78355. }
  78356. // Culling
  78357. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78358. // Managing instances
  78359. var batch = mesh._getInstancesRenderList(subMesh._id);
  78360. if (batch.mustReturn) {
  78361. return;
  78362. }
  78363. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78364. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78365. engine.enableEffect(_this._effect);
  78366. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78367. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78368. _this._effect.setMatrix("view", scene.getViewMatrix());
  78369. // Alpha test
  78370. if (material && material.needAlphaTesting()) {
  78371. var alphaTexture = material.getAlphaTestTexture();
  78372. if (alphaTexture) {
  78373. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78374. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78375. }
  78376. }
  78377. // Bones
  78378. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78379. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78380. }
  78381. // Draw
  78382. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78383. }
  78384. };
  78385. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78386. var index;
  78387. if (depthOnlySubMeshes.length) {
  78388. engine.setColorWrite(false);
  78389. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78390. renderSubMesh(depthOnlySubMeshes.data[index]);
  78391. }
  78392. engine.setColorWrite(true);
  78393. }
  78394. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78395. renderSubMesh(opaqueSubMeshes.data[index]);
  78396. }
  78397. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78398. renderSubMesh(alphaTestSubMeshes.data[index]);
  78399. }
  78400. };
  78401. };
  78402. return GeometryBufferRenderer;
  78403. }());
  78404. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78405. })(BABYLON || (BABYLON = {}));
  78406. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78407. var BABYLON;
  78408. (function (BABYLON) {
  78409. /**
  78410. * This groups together the common properties used for image processing either in direct forward pass
  78411. * or through post processing effect depending on the use of the image processing pipeline in your scene
  78412. * or not.
  78413. */
  78414. var ImageProcessingConfiguration = /** @class */ (function () {
  78415. function ImageProcessingConfiguration() {
  78416. /**
  78417. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  78418. */
  78419. this.colorCurves = new BABYLON.ColorCurves();
  78420. this._colorCurvesEnabled = false;
  78421. this._colorGradingEnabled = false;
  78422. this._colorGradingWithGreenDepth = true;
  78423. this._colorGradingBGR = true;
  78424. this._exposure = 1.0;
  78425. this._toneMappingEnabled = false;
  78426. this._contrast = 1.0;
  78427. /**
  78428. * Vignette stretch size.
  78429. */
  78430. this.vignetteStretch = 0;
  78431. /**
  78432. * Vignette centre X Offset.
  78433. */
  78434. this.vignetteCentreX = 0;
  78435. /**
  78436. * Vignette centre Y Offset.
  78437. */
  78438. this.vignetteCentreY = 0;
  78439. /**
  78440. * Vignette weight or intensity of the vignette effect.
  78441. */
  78442. this.vignetteWeight = 1.5;
  78443. /**
  78444. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78445. * if vignetteEnabled is set to true.
  78446. */
  78447. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78448. /**
  78449. * Camera field of view used by the Vignette effect.
  78450. */
  78451. this.vignetteCameraFov = 0.5;
  78452. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  78453. this._vignetteEnabled = false;
  78454. this._applyByPostProcess = false;
  78455. this._isEnabled = true;
  78456. /**
  78457. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  78458. */
  78459. this.onUpdateParameters = new BABYLON.Observable();
  78460. }
  78461. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  78462. /**
  78463. * Gets wether the color curves effect is enabled.
  78464. */
  78465. get: function () {
  78466. return this._colorCurvesEnabled;
  78467. },
  78468. /**
  78469. * Sets wether the color curves effect is enabled.
  78470. */
  78471. set: function (value) {
  78472. if (this._colorCurvesEnabled === value) {
  78473. return;
  78474. }
  78475. this._colorCurvesEnabled = value;
  78476. this._updateParameters();
  78477. },
  78478. enumerable: true,
  78479. configurable: true
  78480. });
  78481. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  78482. /**
  78483. * Gets wether the color grading effect is enabled.
  78484. */
  78485. get: function () {
  78486. return this._colorGradingEnabled;
  78487. },
  78488. /**
  78489. * Sets wether the color grading effect is enabled.
  78490. */
  78491. set: function (value) {
  78492. if (this._colorGradingEnabled === value) {
  78493. return;
  78494. }
  78495. this._colorGradingEnabled = value;
  78496. this._updateParameters();
  78497. },
  78498. enumerable: true,
  78499. configurable: true
  78500. });
  78501. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  78502. /**
  78503. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  78504. */
  78505. get: function () {
  78506. return this._colorGradingWithGreenDepth;
  78507. },
  78508. /**
  78509. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  78510. */
  78511. set: function (value) {
  78512. if (this._colorGradingWithGreenDepth === value) {
  78513. return;
  78514. }
  78515. this._colorGradingWithGreenDepth = value;
  78516. this._updateParameters();
  78517. },
  78518. enumerable: true,
  78519. configurable: true
  78520. });
  78521. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  78522. /**
  78523. * Gets wether the color grading texture contains BGR values.
  78524. */
  78525. get: function () {
  78526. return this._colorGradingBGR;
  78527. },
  78528. /**
  78529. * Sets wether the color grading texture contains BGR values.
  78530. */
  78531. set: function (value) {
  78532. if (this._colorGradingBGR === value) {
  78533. return;
  78534. }
  78535. this._colorGradingBGR = value;
  78536. this._updateParameters();
  78537. },
  78538. enumerable: true,
  78539. configurable: true
  78540. });
  78541. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  78542. /**
  78543. * Gets the Exposure used in the effect.
  78544. */
  78545. get: function () {
  78546. return this._exposure;
  78547. },
  78548. /**
  78549. * Sets the Exposure used in the effect.
  78550. */
  78551. set: function (value) {
  78552. if (this._exposure === value) {
  78553. return;
  78554. }
  78555. this._exposure = value;
  78556. this._updateParameters();
  78557. },
  78558. enumerable: true,
  78559. configurable: true
  78560. });
  78561. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  78562. /**
  78563. * Gets wether the tone mapping effect is enabled.
  78564. */
  78565. get: function () {
  78566. return this._toneMappingEnabled;
  78567. },
  78568. /**
  78569. * Sets wether the tone mapping effect is enabled.
  78570. */
  78571. set: function (value) {
  78572. if (this._toneMappingEnabled === value) {
  78573. return;
  78574. }
  78575. this._toneMappingEnabled = value;
  78576. this._updateParameters();
  78577. },
  78578. enumerable: true,
  78579. configurable: true
  78580. });
  78581. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  78582. /**
  78583. * Gets the contrast used in the effect.
  78584. */
  78585. get: function () {
  78586. return this._contrast;
  78587. },
  78588. /**
  78589. * Sets the contrast used in the effect.
  78590. */
  78591. set: function (value) {
  78592. if (this._contrast === value) {
  78593. return;
  78594. }
  78595. this._contrast = value;
  78596. this._updateParameters();
  78597. },
  78598. enumerable: true,
  78599. configurable: true
  78600. });
  78601. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  78602. /**
  78603. * Gets the vignette blend mode allowing different kind of effect.
  78604. */
  78605. get: function () {
  78606. return this._vignetteBlendMode;
  78607. },
  78608. /**
  78609. * Sets the vignette blend mode allowing different kind of effect.
  78610. */
  78611. set: function (value) {
  78612. if (this._vignetteBlendMode === value) {
  78613. return;
  78614. }
  78615. this._vignetteBlendMode = value;
  78616. this._updateParameters();
  78617. },
  78618. enumerable: true,
  78619. configurable: true
  78620. });
  78621. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  78622. /**
  78623. * Gets wether the vignette effect is enabled.
  78624. */
  78625. get: function () {
  78626. return this._vignetteEnabled;
  78627. },
  78628. /**
  78629. * Sets wether the vignette effect is enabled.
  78630. */
  78631. set: function (value) {
  78632. if (this._vignetteEnabled === value) {
  78633. return;
  78634. }
  78635. this._vignetteEnabled = value;
  78636. this._updateParameters();
  78637. },
  78638. enumerable: true,
  78639. configurable: true
  78640. });
  78641. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  78642. /**
  78643. * Gets wether the image processing is applied through a post process or not.
  78644. */
  78645. get: function () {
  78646. return this._applyByPostProcess;
  78647. },
  78648. /**
  78649. * Sets wether the image processing is applied through a post process or not.
  78650. */
  78651. set: function (value) {
  78652. if (this._applyByPostProcess === value) {
  78653. return;
  78654. }
  78655. this._applyByPostProcess = value;
  78656. this._updateParameters();
  78657. },
  78658. enumerable: true,
  78659. configurable: true
  78660. });
  78661. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  78662. /**
  78663. * Gets wether the image processing is enabled or not.
  78664. */
  78665. get: function () {
  78666. return this._isEnabled;
  78667. },
  78668. /**
  78669. * Sets wether the image processing is enabled or not.
  78670. */
  78671. set: function (value) {
  78672. if (this._isEnabled === value) {
  78673. return;
  78674. }
  78675. this._isEnabled = value;
  78676. this._updateParameters();
  78677. },
  78678. enumerable: true,
  78679. configurable: true
  78680. });
  78681. /**
  78682. * Method called each time the image processing information changes requires to recompile the effect.
  78683. */
  78684. ImageProcessingConfiguration.prototype._updateParameters = function () {
  78685. this.onUpdateParameters.notifyObservers(this);
  78686. };
  78687. ImageProcessingConfiguration.prototype.getClassName = function () {
  78688. return "ImageProcessingConfiguration";
  78689. };
  78690. /**
  78691. * Prepare the list of uniforms associated with the Image Processing effects.
  78692. * @param uniformsList The list of uniforms used in the effect
  78693. * @param defines the list of defines currently in use
  78694. */
  78695. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  78696. if (defines.EXPOSURE) {
  78697. uniforms.push("exposureLinear");
  78698. }
  78699. if (defines.CONTRAST) {
  78700. uniforms.push("contrast");
  78701. }
  78702. if (defines.COLORGRADING) {
  78703. uniforms.push("colorTransformSettings");
  78704. }
  78705. if (defines.VIGNETTE) {
  78706. uniforms.push("vInverseScreenSize");
  78707. uniforms.push("vignetteSettings1");
  78708. uniforms.push("vignetteSettings2");
  78709. }
  78710. if (defines.COLORCURVES) {
  78711. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  78712. }
  78713. };
  78714. /**
  78715. * Prepare the list of samplers associated with the Image Processing effects.
  78716. * @param uniformsList The list of uniforms used in the effect
  78717. * @param defines the list of defines currently in use
  78718. */
  78719. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  78720. if (defines.COLORGRADING) {
  78721. samplersList.push("txColorTransform");
  78722. }
  78723. };
  78724. /**
  78725. * Prepare the list of defines associated to the shader.
  78726. * @param defines the list of defines to complete
  78727. */
  78728. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  78729. if (forPostProcess === void 0) { forPostProcess = false; }
  78730. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  78731. defines.VIGNETTE = false;
  78732. defines.TONEMAPPING = false;
  78733. defines.CONTRAST = false;
  78734. defines.EXPOSURE = false;
  78735. defines.COLORCURVES = false;
  78736. defines.COLORGRADING = false;
  78737. defines.COLORGRADING3D = false;
  78738. defines.IMAGEPROCESSING = false;
  78739. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  78740. return;
  78741. }
  78742. defines.VIGNETTE = this.vignetteEnabled;
  78743. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  78744. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  78745. defines.TONEMAPPING = this.toneMappingEnabled;
  78746. defines.CONTRAST = (this.contrast !== 1.0);
  78747. defines.EXPOSURE = (this.exposure !== 1.0);
  78748. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  78749. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  78750. if (defines.COLORGRADING) {
  78751. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  78752. }
  78753. else {
  78754. defines.COLORGRADING3D = false;
  78755. }
  78756. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  78757. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  78758. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  78759. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  78760. };
  78761. /**
  78762. * Returns true if all the image processing information are ready.
  78763. */
  78764. ImageProcessingConfiguration.prototype.isReady = function () {
  78765. // Color Grading texure can not be none blocking.
  78766. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  78767. };
  78768. /**
  78769. * Binds the image processing to the shader.
  78770. * @param effect The effect to bind to
  78771. */
  78772. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  78773. if (aspectRatio === void 0) { aspectRatio = 1; }
  78774. // Color Curves
  78775. if (this._colorCurvesEnabled && this.colorCurves) {
  78776. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  78777. }
  78778. // Vignette
  78779. if (this._vignetteEnabled) {
  78780. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  78781. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  78782. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  78783. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  78784. var vignetteScaleX = vignetteScaleY * aspectRatio;
  78785. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  78786. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  78787. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  78788. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  78789. var vignettePower = -2.0 * this.vignetteWeight;
  78790. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  78791. }
  78792. // Exposure
  78793. effect.setFloat("exposureLinear", this.exposure);
  78794. // Contrast
  78795. effect.setFloat("contrast", this.contrast);
  78796. // Color transform settings
  78797. if (this.colorGradingTexture) {
  78798. effect.setTexture("txColorTransform", this.colorGradingTexture);
  78799. var textureSize = this.colorGradingTexture.getSize().height;
  78800. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  78801. 0.5 / textureSize, // textureOffset
  78802. textureSize, // textureSize
  78803. this.colorGradingTexture.level // weight
  78804. );
  78805. }
  78806. };
  78807. /**
  78808. * Clones the current image processing instance.
  78809. * @return The cloned image processing
  78810. */
  78811. ImageProcessingConfiguration.prototype.clone = function () {
  78812. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  78813. };
  78814. /**
  78815. * Serializes the current image processing instance to a json representation.
  78816. * @return a JSON representation
  78817. */
  78818. ImageProcessingConfiguration.prototype.serialize = function () {
  78819. return BABYLON.SerializationHelper.Serialize(this);
  78820. };
  78821. /**
  78822. * Parses the image processing from a json representation.
  78823. * @param source the JSON source to parse
  78824. * @return The parsed image processing
  78825. */
  78826. ImageProcessingConfiguration.Parse = function (source) {
  78827. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  78828. };
  78829. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  78830. /**
  78831. * Used to apply the vignette as a mix with the pixel color.
  78832. */
  78833. get: function () {
  78834. return this._VIGNETTEMODE_MULTIPLY;
  78835. },
  78836. enumerable: true,
  78837. configurable: true
  78838. });
  78839. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  78840. /**
  78841. * Used to apply the vignette as a replacement of the pixel color.
  78842. */
  78843. get: function () {
  78844. return this._VIGNETTEMODE_OPAQUE;
  78845. },
  78846. enumerable: true,
  78847. configurable: true
  78848. });
  78849. // Static constants associated to the image processing.
  78850. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  78851. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  78852. __decorate([
  78853. BABYLON.serializeAsColorCurves()
  78854. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  78855. __decorate([
  78856. BABYLON.serialize()
  78857. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  78858. __decorate([
  78859. BABYLON.serializeAsTexture()
  78860. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  78861. __decorate([
  78862. BABYLON.serialize()
  78863. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  78864. __decorate([
  78865. BABYLON.serialize()
  78866. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  78867. __decorate([
  78868. BABYLON.serialize()
  78869. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  78870. __decorate([
  78871. BABYLON.serialize()
  78872. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  78873. __decorate([
  78874. BABYLON.serialize()
  78875. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  78876. __decorate([
  78877. BABYLON.serialize()
  78878. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  78879. __decorate([
  78880. BABYLON.serialize()
  78881. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  78882. __decorate([
  78883. BABYLON.serialize()
  78884. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  78885. __decorate([
  78886. BABYLON.serialize()
  78887. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  78888. __decorate([
  78889. BABYLON.serialize()
  78890. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  78891. __decorate([
  78892. BABYLON.serializeAsColor4()
  78893. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  78894. __decorate([
  78895. BABYLON.serialize()
  78896. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  78897. __decorate([
  78898. BABYLON.serialize()
  78899. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  78900. __decorate([
  78901. BABYLON.serialize()
  78902. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  78903. __decorate([
  78904. BABYLON.serialize()
  78905. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  78906. __decorate([
  78907. BABYLON.serialize()
  78908. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  78909. return ImageProcessingConfiguration;
  78910. }());
  78911. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  78912. })(BABYLON || (BABYLON = {}));
  78913. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  78914. var BABYLON;
  78915. (function (BABYLON) {
  78916. /**
  78917. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  78918. * It can help converting any input color in a desired output one. This can then be used to create effects
  78919. * from sepia, black and white to sixties or futuristic rendering...
  78920. *
  78921. * The only supported format is currently 3dl.
  78922. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  78923. */
  78924. var ColorGradingTexture = /** @class */ (function (_super) {
  78925. __extends(ColorGradingTexture, _super);
  78926. /**
  78927. * Instantiates a ColorGradingTexture from the following parameters.
  78928. *
  78929. * @param url The location of the color gradind data (currently only supporting 3dl)
  78930. * @param scene The scene the texture will be used in
  78931. */
  78932. function ColorGradingTexture(url, scene) {
  78933. var _this = _super.call(this, scene) || this;
  78934. if (!url) {
  78935. return _this;
  78936. }
  78937. _this._engine = scene.getEngine();
  78938. _this._textureMatrix = BABYLON.Matrix.Identity();
  78939. _this.name = url;
  78940. _this.url = url;
  78941. _this.hasAlpha = false;
  78942. _this.isCube = false;
  78943. _this.is3D = _this._engine.webGLVersion > 1;
  78944. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78945. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78946. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78947. _this.anisotropicFilteringLevel = 1;
  78948. _this._texture = _this._getFromCache(url, true);
  78949. if (!_this._texture) {
  78950. if (!scene.useDelayedTextureLoading) {
  78951. _this.loadTexture();
  78952. }
  78953. else {
  78954. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78955. }
  78956. }
  78957. return _this;
  78958. }
  78959. /**
  78960. * Returns the texture matrix used in most of the material.
  78961. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  78962. */
  78963. ColorGradingTexture.prototype.getTextureMatrix = function () {
  78964. return this._textureMatrix;
  78965. };
  78966. /**
  78967. * Occurs when the file being loaded is a .3dl LUT file.
  78968. */
  78969. ColorGradingTexture.prototype.load3dlTexture = function () {
  78970. var engine = this._engine;
  78971. var texture;
  78972. if (engine.webGLVersion === 1) {
  78973. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78974. }
  78975. else {
  78976. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78977. }
  78978. this._texture = texture;
  78979. var callback = function (text) {
  78980. if (typeof text !== "string") {
  78981. return;
  78982. }
  78983. var data = null;
  78984. var tempData = null;
  78985. var line;
  78986. var lines = text.split('\n');
  78987. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  78988. var maxColor = 0;
  78989. for (var i = 0; i < lines.length; i++) {
  78990. line = lines[i];
  78991. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  78992. continue;
  78993. if (line.indexOf('#') === 0)
  78994. continue;
  78995. var words = line.split(" ");
  78996. if (size === 0) {
  78997. // Number of space + one
  78998. size = words.length;
  78999. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  79000. tempData = new Float32Array(size * size * size * 4);
  79001. continue;
  79002. }
  79003. if (size != 0) {
  79004. var r = Math.max(parseInt(words[0]), 0);
  79005. var g = Math.max(parseInt(words[1]), 0);
  79006. var b = Math.max(parseInt(words[2]), 0);
  79007. maxColor = Math.max(r, maxColor);
  79008. maxColor = Math.max(g, maxColor);
  79009. maxColor = Math.max(b, maxColor);
  79010. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  79011. if (tempData) {
  79012. tempData[pixelStorageIndex + 0] = r;
  79013. tempData[pixelStorageIndex + 1] = g;
  79014. tempData[pixelStorageIndex + 2] = b;
  79015. }
  79016. pixelIndexSlice++;
  79017. if (pixelIndexSlice % size == 0) {
  79018. pixelIndexH++;
  79019. pixelIndexSlice = 0;
  79020. if (pixelIndexH % size == 0) {
  79021. pixelIndexW++;
  79022. pixelIndexH = 0;
  79023. }
  79024. }
  79025. }
  79026. }
  79027. if (tempData && data) {
  79028. for (var i = 0; i < tempData.length; i++) {
  79029. if (i > 0 && (i + 1) % 4 === 0) {
  79030. data[i] = 255;
  79031. }
  79032. else {
  79033. var value = tempData[i];
  79034. data[i] = (value / maxColor * 255);
  79035. }
  79036. }
  79037. }
  79038. if (texture.is3D) {
  79039. texture.updateSize(size, size, size);
  79040. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79041. }
  79042. else {
  79043. texture.updateSize(size * size, size);
  79044. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79045. }
  79046. };
  79047. var scene = this.getScene();
  79048. if (scene) {
  79049. scene._loadFile(this.url, callback);
  79050. }
  79051. else {
  79052. this._engine._loadFile(this.url, callback);
  79053. }
  79054. return this._texture;
  79055. };
  79056. /**
  79057. * Starts the loading process of the texture.
  79058. */
  79059. ColorGradingTexture.prototype.loadTexture = function () {
  79060. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  79061. this.load3dlTexture();
  79062. }
  79063. };
  79064. /**
  79065. * Clones the color gradind texture.
  79066. */
  79067. ColorGradingTexture.prototype.clone = function () {
  79068. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  79069. // Base texture
  79070. newTexture.level = this.level;
  79071. return newTexture;
  79072. };
  79073. /**
  79074. * Called during delayed load for textures.
  79075. */
  79076. ColorGradingTexture.prototype.delayLoad = function () {
  79077. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79078. return;
  79079. }
  79080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79081. this._texture = this._getFromCache(this.url, true);
  79082. if (!this._texture) {
  79083. this.loadTexture();
  79084. }
  79085. };
  79086. /**
  79087. * Parses a color grading texture serialized by Babylon.
  79088. * @param parsedTexture The texture information being parsedTexture
  79089. * @param scene The scene to load the texture in
  79090. * @param rootUrl The root url of the data assets to load
  79091. * @return A color gradind texture
  79092. */
  79093. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79094. var texture = null;
  79095. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79096. texture = new ColorGradingTexture(parsedTexture.name, scene);
  79097. texture.name = parsedTexture.name;
  79098. texture.level = parsedTexture.level;
  79099. }
  79100. return texture;
  79101. };
  79102. /**
  79103. * Serializes the LUT texture to json format.
  79104. */
  79105. ColorGradingTexture.prototype.serialize = function () {
  79106. if (!this.name) {
  79107. return null;
  79108. }
  79109. var serializationObject = {};
  79110. serializationObject.name = this.name;
  79111. serializationObject.level = this.level;
  79112. serializationObject.customType = "BABYLON.ColorGradingTexture";
  79113. return serializationObject;
  79114. };
  79115. /**
  79116. * Empty line regex stored for GC.
  79117. */
  79118. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  79119. return ColorGradingTexture;
  79120. }(BABYLON.BaseTexture));
  79121. BABYLON.ColorGradingTexture = ColorGradingTexture;
  79122. })(BABYLON || (BABYLON = {}));
  79123. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  79124. var BABYLON;
  79125. (function (BABYLON) {
  79126. /**
  79127. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79128. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79129. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  79130. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79131. */
  79132. var ColorCurves = /** @class */ (function () {
  79133. function ColorCurves() {
  79134. this._dirty = true;
  79135. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  79136. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  79137. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79138. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  79139. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79140. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  79141. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  79142. this._globalHue = 30;
  79143. this._globalDensity = 0;
  79144. this._globalSaturation = 0;
  79145. this._globalExposure = 0;
  79146. this._highlightsHue = 30;
  79147. this._highlightsDensity = 0;
  79148. this._highlightsSaturation = 0;
  79149. this._highlightsExposure = 0;
  79150. this._midtonesHue = 30;
  79151. this._midtonesDensity = 0;
  79152. this._midtonesSaturation = 0;
  79153. this._midtonesExposure = 0;
  79154. this._shadowsHue = 30;
  79155. this._shadowsDensity = 0;
  79156. this._shadowsSaturation = 0;
  79157. this._shadowsExposure = 0;
  79158. }
  79159. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  79160. /**
  79161. * Gets the global Hue value.
  79162. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  79163. */
  79164. get: function () {
  79165. return this._globalHue;
  79166. },
  79167. /**
  79168. * Sets the global Hue value.
  79169. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  79170. */
  79171. set: function (value) {
  79172. this._globalHue = value;
  79173. this._dirty = true;
  79174. },
  79175. enumerable: true,
  79176. configurable: true
  79177. });
  79178. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  79179. /**
  79180. * Gets the global Density value.
  79181. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  79182. * Values less than zero provide a filter of opposite hue.
  79183. */
  79184. get: function () {
  79185. return this._globalDensity;
  79186. },
  79187. /**
  79188. * Sets the global Density value.
  79189. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  79190. * Values less than zero provide a filter of opposite hue.
  79191. */
  79192. set: function (value) {
  79193. this._globalDensity = value;
  79194. this._dirty = true;
  79195. },
  79196. enumerable: true,
  79197. configurable: true
  79198. });
  79199. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  79200. /**
  79201. * Gets the global Saturation value.
  79202. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  79203. */
  79204. get: function () {
  79205. return this._globalSaturation;
  79206. },
  79207. /**
  79208. * Sets the global Saturation value.
  79209. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  79210. */
  79211. set: function (value) {
  79212. this._globalSaturation = value;
  79213. this._dirty = true;
  79214. },
  79215. enumerable: true,
  79216. configurable: true
  79217. });
  79218. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  79219. /**
  79220. * Gets the global Exposure value.
  79221. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  79222. */
  79223. get: function () {
  79224. return this._globalExposure;
  79225. },
  79226. /**
  79227. * Sets the global Exposure value.
  79228. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  79229. */
  79230. set: function (value) {
  79231. this._globalExposure = value;
  79232. this._dirty = true;
  79233. },
  79234. enumerable: true,
  79235. configurable: true
  79236. });
  79237. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  79238. /**
  79239. * Gets the highlights Hue value.
  79240. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  79241. */
  79242. get: function () {
  79243. return this._highlightsHue;
  79244. },
  79245. /**
  79246. * Sets the highlights Hue value.
  79247. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  79248. */
  79249. set: function (value) {
  79250. this._highlightsHue = value;
  79251. this._dirty = true;
  79252. },
  79253. enumerable: true,
  79254. configurable: true
  79255. });
  79256. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  79257. /**
  79258. * Gets the highlights Density value.
  79259. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  79260. * Values less than zero provide a filter of opposite hue.
  79261. */
  79262. get: function () {
  79263. return this._highlightsDensity;
  79264. },
  79265. /**
  79266. * Sets the highlights Density value.
  79267. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  79268. * Values less than zero provide a filter of opposite hue.
  79269. */
  79270. set: function (value) {
  79271. this._highlightsDensity = value;
  79272. this._dirty = true;
  79273. },
  79274. enumerable: true,
  79275. configurable: true
  79276. });
  79277. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  79278. /**
  79279. * Gets the highlights Saturation value.
  79280. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  79281. */
  79282. get: function () {
  79283. return this._highlightsSaturation;
  79284. },
  79285. /**
  79286. * Sets the highlights Saturation value.
  79287. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  79288. */
  79289. set: function (value) {
  79290. this._highlightsSaturation = value;
  79291. this._dirty = true;
  79292. },
  79293. enumerable: true,
  79294. configurable: true
  79295. });
  79296. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  79297. /**
  79298. * Gets the highlights Exposure value.
  79299. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  79300. */
  79301. get: function () {
  79302. return this._highlightsExposure;
  79303. },
  79304. /**
  79305. * Sets the highlights Exposure value.
  79306. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  79307. */
  79308. set: function (value) {
  79309. this._highlightsExposure = value;
  79310. this._dirty = true;
  79311. },
  79312. enumerable: true,
  79313. configurable: true
  79314. });
  79315. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  79316. /**
  79317. * Gets the midtones Hue value.
  79318. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  79319. */
  79320. get: function () {
  79321. return this._midtonesHue;
  79322. },
  79323. /**
  79324. * Sets the midtones Hue value.
  79325. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  79326. */
  79327. set: function (value) {
  79328. this._midtonesHue = value;
  79329. this._dirty = true;
  79330. },
  79331. enumerable: true,
  79332. configurable: true
  79333. });
  79334. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  79335. /**
  79336. * Gets the midtones Density value.
  79337. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  79338. * Values less than zero provide a filter of opposite hue.
  79339. */
  79340. get: function () {
  79341. return this._midtonesDensity;
  79342. },
  79343. /**
  79344. * Sets the midtones Density value.
  79345. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  79346. * Values less than zero provide a filter of opposite hue.
  79347. */
  79348. set: function (value) {
  79349. this._midtonesDensity = value;
  79350. this._dirty = true;
  79351. },
  79352. enumerable: true,
  79353. configurable: true
  79354. });
  79355. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  79356. /**
  79357. * Gets the midtones Saturation value.
  79358. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  79359. */
  79360. get: function () {
  79361. return this._midtonesSaturation;
  79362. },
  79363. /**
  79364. * Sets the midtones Saturation value.
  79365. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  79366. */
  79367. set: function (value) {
  79368. this._midtonesSaturation = value;
  79369. this._dirty = true;
  79370. },
  79371. enumerable: true,
  79372. configurable: true
  79373. });
  79374. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  79375. /**
  79376. * Gets the midtones Exposure value.
  79377. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  79378. */
  79379. get: function () {
  79380. return this._midtonesExposure;
  79381. },
  79382. /**
  79383. * Sets the midtones Exposure value.
  79384. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  79385. */
  79386. set: function (value) {
  79387. this._midtonesExposure = value;
  79388. this._dirty = true;
  79389. },
  79390. enumerable: true,
  79391. configurable: true
  79392. });
  79393. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  79394. /**
  79395. * Gets the shadows Hue value.
  79396. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  79397. */
  79398. get: function () {
  79399. return this._shadowsHue;
  79400. },
  79401. /**
  79402. * Sets the shadows Hue value.
  79403. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  79404. */
  79405. set: function (value) {
  79406. this._shadowsHue = value;
  79407. this._dirty = true;
  79408. },
  79409. enumerable: true,
  79410. configurable: true
  79411. });
  79412. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  79413. /**
  79414. * Gets the shadows Density value.
  79415. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  79416. * Values less than zero provide a filter of opposite hue.
  79417. */
  79418. get: function () {
  79419. return this._shadowsDensity;
  79420. },
  79421. /**
  79422. * Sets the shadows Density value.
  79423. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  79424. * Values less than zero provide a filter of opposite hue.
  79425. */
  79426. set: function (value) {
  79427. this._shadowsDensity = value;
  79428. this._dirty = true;
  79429. },
  79430. enumerable: true,
  79431. configurable: true
  79432. });
  79433. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  79434. /**
  79435. * Gets the shadows Saturation value.
  79436. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  79437. */
  79438. get: function () {
  79439. return this._shadowsSaturation;
  79440. },
  79441. /**
  79442. * Sets the shadows Saturation value.
  79443. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  79444. */
  79445. set: function (value) {
  79446. this._shadowsSaturation = value;
  79447. this._dirty = true;
  79448. },
  79449. enumerable: true,
  79450. configurable: true
  79451. });
  79452. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  79453. /**
  79454. * Gets the shadows Exposure value.
  79455. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  79456. */
  79457. get: function () {
  79458. return this._shadowsExposure;
  79459. },
  79460. /**
  79461. * Sets the shadows Exposure value.
  79462. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  79463. */
  79464. set: function (value) {
  79465. this._shadowsExposure = value;
  79466. this._dirty = true;
  79467. },
  79468. enumerable: true,
  79469. configurable: true
  79470. });
  79471. ColorCurves.prototype.getClassName = function () {
  79472. return "ColorCurves";
  79473. };
  79474. /**
  79475. * Binds the color curves to the shader.
  79476. * @param colorCurves The color curve to bind
  79477. * @param effect The effect to bind to
  79478. */
  79479. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  79480. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  79481. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  79482. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  79483. if (colorCurves._dirty) {
  79484. colorCurves._dirty = false;
  79485. // Fill in global info.
  79486. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  79487. // Compute highlights info.
  79488. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  79489. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  79490. // Compute midtones info.
  79491. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  79492. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  79493. // Compute shadows info.
  79494. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  79495. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  79496. // Compute deltas (neutral is midtones).
  79497. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  79498. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  79499. }
  79500. if (effect) {
  79501. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  79502. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  79503. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  79504. }
  79505. };
  79506. /**
  79507. * Prepare the list of uniforms associated with the ColorCurves effects.
  79508. * @param uniformsList The list of uniforms used in the effect
  79509. */
  79510. ColorCurves.PrepareUniforms = function (uniformsList) {
  79511. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  79512. };
  79513. /**
  79514. * Returns color grading data based on a hue, density, saturation and exposure value.
  79515. * @param filterHue The hue of the color filter.
  79516. * @param filterDensity The density of the color filter.
  79517. * @param saturation The saturation.
  79518. * @param exposure The exposure.
  79519. * @param result The result data container.
  79520. */
  79521. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  79522. if (hue == null) {
  79523. return;
  79524. }
  79525. hue = ColorCurves.clamp(hue, 0, 360);
  79526. density = ColorCurves.clamp(density, -100, 100);
  79527. saturation = ColorCurves.clamp(saturation, -100, 100);
  79528. exposure = ColorCurves.clamp(exposure, -100, 100);
  79529. // Remap the slider/config filter density with non-linear mapping and also scale by half
  79530. // so that the maximum filter density is only 50% control. This provides fine control
  79531. // for small values and reasonable range.
  79532. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  79533. density *= 0.5;
  79534. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  79535. if (density < 0) {
  79536. density *= -1;
  79537. hue = (hue + 180) % 360;
  79538. }
  79539. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  79540. result.scaleToRef(2, result);
  79541. result.a = 1 + 0.01 * saturation;
  79542. };
  79543. /**
  79544. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  79545. * @param value The input slider value in range [-100,100].
  79546. * @returns Adjusted value.
  79547. */
  79548. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  79549. value /= 100;
  79550. var x = Math.abs(value);
  79551. x = Math.pow(x, 2);
  79552. if (value < 0) {
  79553. x *= -1;
  79554. }
  79555. x *= 100;
  79556. return x;
  79557. };
  79558. /**
  79559. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  79560. * @param hue The hue (H) input.
  79561. * @param saturation The saturation (S) input.
  79562. * @param brightness The brightness (B) input.
  79563. * @result An RGBA color represented as Vector4.
  79564. */
  79565. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  79566. var h = ColorCurves.clamp(hue, 0, 360);
  79567. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  79568. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  79569. if (s === 0) {
  79570. result.r = v;
  79571. result.g = v;
  79572. result.b = v;
  79573. }
  79574. else {
  79575. // sector 0 to 5
  79576. h /= 60;
  79577. var i = Math.floor(h);
  79578. // fractional part of h
  79579. var f = h - i;
  79580. var p = v * (1 - s);
  79581. var q = v * (1 - s * f);
  79582. var t = v * (1 - s * (1 - f));
  79583. switch (i) {
  79584. case 0:
  79585. result.r = v;
  79586. result.g = t;
  79587. result.b = p;
  79588. break;
  79589. case 1:
  79590. result.r = q;
  79591. result.g = v;
  79592. result.b = p;
  79593. break;
  79594. case 2:
  79595. result.r = p;
  79596. result.g = v;
  79597. result.b = t;
  79598. break;
  79599. case 3:
  79600. result.r = p;
  79601. result.g = q;
  79602. result.b = v;
  79603. break;
  79604. case 4:
  79605. result.r = t;
  79606. result.g = p;
  79607. result.b = v;
  79608. break;
  79609. default: // case 5:
  79610. result.r = v;
  79611. result.g = p;
  79612. result.b = q;
  79613. break;
  79614. }
  79615. }
  79616. result.a = 1;
  79617. };
  79618. /**
  79619. * Returns a value clamped between min and max
  79620. * @param value The value to clamp
  79621. * @param min The minimum of value
  79622. * @param max The maximum of value
  79623. * @returns The clamped value.
  79624. */
  79625. ColorCurves.clamp = function (value, min, max) {
  79626. return Math.min(Math.max(value, min), max);
  79627. };
  79628. /**
  79629. * Clones the current color curve instance.
  79630. * @return The cloned curves
  79631. */
  79632. ColorCurves.prototype.clone = function () {
  79633. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  79634. };
  79635. /**
  79636. * Serializes the current color curve instance to a json representation.
  79637. * @return a JSON representation
  79638. */
  79639. ColorCurves.prototype.serialize = function () {
  79640. return BABYLON.SerializationHelper.Serialize(this);
  79641. };
  79642. /**
  79643. * Parses the color curve from a json representation.
  79644. * @param source the JSON source to parse
  79645. * @return The parsed curves
  79646. */
  79647. ColorCurves.Parse = function (source) {
  79648. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  79649. };
  79650. __decorate([
  79651. BABYLON.serialize()
  79652. ], ColorCurves.prototype, "_globalHue", void 0);
  79653. __decorate([
  79654. BABYLON.serialize()
  79655. ], ColorCurves.prototype, "_globalDensity", void 0);
  79656. __decorate([
  79657. BABYLON.serialize()
  79658. ], ColorCurves.prototype, "_globalSaturation", void 0);
  79659. __decorate([
  79660. BABYLON.serialize()
  79661. ], ColorCurves.prototype, "_globalExposure", void 0);
  79662. __decorate([
  79663. BABYLON.serialize()
  79664. ], ColorCurves.prototype, "_highlightsHue", void 0);
  79665. __decorate([
  79666. BABYLON.serialize()
  79667. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  79668. __decorate([
  79669. BABYLON.serialize()
  79670. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  79671. __decorate([
  79672. BABYLON.serialize()
  79673. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  79674. __decorate([
  79675. BABYLON.serialize()
  79676. ], ColorCurves.prototype, "_midtonesHue", void 0);
  79677. __decorate([
  79678. BABYLON.serialize()
  79679. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  79680. __decorate([
  79681. BABYLON.serialize()
  79682. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  79683. __decorate([
  79684. BABYLON.serialize()
  79685. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  79686. return ColorCurves;
  79687. }());
  79688. BABYLON.ColorCurves = ColorCurves;
  79689. })(BABYLON || (BABYLON = {}));
  79690. //# sourceMappingURL=babylon.colorCurves.js.map
  79691. var BABYLON;
  79692. (function (BABYLON) {
  79693. var RefractionPostProcess = /** @class */ (function (_super) {
  79694. __extends(RefractionPostProcess, _super);
  79695. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  79696. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  79697. _this.color = color;
  79698. _this.depth = depth;
  79699. _this.colorLevel = colorLevel;
  79700. _this._ownRefractionTexture = true;
  79701. _this.onActivateObservable.add(function (cam) {
  79702. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  79703. });
  79704. _this.onApplyObservable.add(function (effect) {
  79705. effect.setColor3("baseColor", _this.color);
  79706. effect.setFloat("depth", _this.depth);
  79707. effect.setFloat("colorLevel", _this.colorLevel);
  79708. effect.setTexture("refractionSampler", _this._refTexture);
  79709. });
  79710. return _this;
  79711. }
  79712. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  79713. /**
  79714. * Gets or sets the refraction texture
  79715. * Please note that you are responsible for disposing the texture if you set it manually
  79716. */
  79717. get: function () {
  79718. return this._refTexture;
  79719. },
  79720. set: function (value) {
  79721. if (this._refTexture && this._ownRefractionTexture) {
  79722. this._refTexture.dispose();
  79723. }
  79724. this._refTexture = value;
  79725. this._ownRefractionTexture = false;
  79726. },
  79727. enumerable: true,
  79728. configurable: true
  79729. });
  79730. // Methods
  79731. RefractionPostProcess.prototype.dispose = function (camera) {
  79732. if (this._refTexture && this._ownRefractionTexture) {
  79733. this._refTexture.dispose();
  79734. this._refTexture = null;
  79735. }
  79736. _super.prototype.dispose.call(this, camera);
  79737. };
  79738. return RefractionPostProcess;
  79739. }(BABYLON.PostProcess));
  79740. BABYLON.RefractionPostProcess = RefractionPostProcess;
  79741. })(BABYLON || (BABYLON = {}));
  79742. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  79743. var BABYLON;
  79744. (function (BABYLON) {
  79745. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  79746. __extends(BlackAndWhitePostProcess, _super);
  79747. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  79748. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  79749. _this.degree = 1;
  79750. _this.onApplyObservable.add(function (effect) {
  79751. effect.setFloat("degree", _this.degree);
  79752. });
  79753. return _this;
  79754. }
  79755. return BlackAndWhitePostProcess;
  79756. }(BABYLON.PostProcess));
  79757. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  79758. })(BABYLON || (BABYLON = {}));
  79759. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  79760. var BABYLON;
  79761. (function (BABYLON) {
  79762. /**
  79763. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  79764. * input texture to perform effects such as edge detection or sharpening
  79765. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  79766. */
  79767. var ConvolutionPostProcess = /** @class */ (function (_super) {
  79768. __extends(ConvolutionPostProcess, _super);
  79769. /**
  79770. * Creates a new instance ConvolutionPostProcess
  79771. * @param name The name of the effect.
  79772. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  79773. * @param options The required width/height ratio to downsize to before computing the render pass.
  79774. * @param camera The camera to apply the render pass to.
  79775. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79776. * @param engine The engine which the post process will be applied. (default: current engine)
  79777. * @param reusable If the post process can be reused on the same frame. (default: false)
  79778. * @param textureType Type of textures used when performing the post process. (default: 0)
  79779. */
  79780. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  79781. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79782. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79783. _this.kernel = kernel;
  79784. _this.onApply = function (effect) {
  79785. effect.setFloat2("screenSize", _this.width, _this.height);
  79786. effect.setArray("kernel", _this.kernel);
  79787. };
  79788. return _this;
  79789. }
  79790. // Statics
  79791. /**
  79792. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79793. */
  79794. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  79795. /**
  79796. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79797. */
  79798. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  79799. /**
  79800. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79801. */
  79802. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  79803. /**
  79804. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79805. */
  79806. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  79807. /**
  79808. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79809. */
  79810. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  79811. /**
  79812. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79813. */
  79814. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  79815. return ConvolutionPostProcess;
  79816. }(BABYLON.PostProcess));
  79817. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  79818. })(BABYLON || (BABYLON = {}));
  79819. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  79820. var BABYLON;
  79821. (function (BABYLON) {
  79822. var FilterPostProcess = /** @class */ (function (_super) {
  79823. __extends(FilterPostProcess, _super);
  79824. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  79825. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  79826. _this.kernelMatrix = kernelMatrix;
  79827. _this.onApply = function (effect) {
  79828. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  79829. };
  79830. return _this;
  79831. }
  79832. return FilterPostProcess;
  79833. }(BABYLON.PostProcess));
  79834. BABYLON.FilterPostProcess = FilterPostProcess;
  79835. })(BABYLON || (BABYLON = {}));
  79836. //# sourceMappingURL=babylon.filterPostProcess.js.map
  79837. var BABYLON;
  79838. (function (BABYLON) {
  79839. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  79840. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  79841. __extends(VolumetricLightScatteringPostProcess, _super);
  79842. /**
  79843. * @constructor
  79844. * @param {string} name - The post-process name
  79845. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  79846. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  79847. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  79848. * @param {number} samples - The post-process quality, default 100
  79849. * @param {number} samplingMode - The post-process filtering mode
  79850. * @param {BABYLON.Engine} engine - The babylon engine
  79851. * @param {boolean} reusable - If the post-process is reusable
  79852. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  79853. */
  79854. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  79855. if (samples === void 0) { samples = 100; }
  79856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79857. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  79858. _this._screenCoordinates = BABYLON.Vector2.Zero();
  79859. /**
  79860. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  79861. */
  79862. _this.customMeshPosition = BABYLON.Vector3.Zero();
  79863. /**
  79864. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  79865. */
  79866. _this.useCustomMeshPosition = false;
  79867. /**
  79868. * If the post-process should inverse the light scattering direction
  79869. */
  79870. _this.invert = true;
  79871. /**
  79872. * Array containing the excluded meshes not rendered in the internal pass
  79873. */
  79874. _this.excludedMeshes = new Array();
  79875. /**
  79876. * Controls the overall intensity of the post-process
  79877. */
  79878. _this.exposure = 0.3;
  79879. /**
  79880. * Dissipates each sample's contribution in range [0, 1]
  79881. */
  79882. _this.decay = 0.96815;
  79883. /**
  79884. * Controls the overall intensity of each sample
  79885. */
  79886. _this.weight = 0.58767;
  79887. /**
  79888. * Controls the density of each sample
  79889. */
  79890. _this.density = 0.926;
  79891. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  79892. engine = scene.getEngine();
  79893. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  79894. // Configure mesh
  79895. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  79896. // Configure
  79897. _this._createPass(scene, ratio.passRatio || ratio);
  79898. _this.onActivate = function (camera) {
  79899. if (!_this.isSupported) {
  79900. _this.dispose(camera);
  79901. }
  79902. _this.onActivate = null;
  79903. };
  79904. _this.onApplyObservable.add(function (effect) {
  79905. _this._updateMeshScreenCoordinates(scene);
  79906. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  79907. effect.setFloat("exposure", _this.exposure);
  79908. effect.setFloat("decay", _this.decay);
  79909. effect.setFloat("weight", _this.weight);
  79910. effect.setFloat("density", _this.density);
  79911. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  79912. });
  79913. return _this;
  79914. }
  79915. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  79916. get: function () {
  79917. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79918. return false;
  79919. },
  79920. set: function (useDiffuseColor) {
  79921. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79922. },
  79923. enumerable: true,
  79924. configurable: true
  79925. });
  79926. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  79927. return "VolumetricLightScatteringPostProcess";
  79928. };
  79929. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  79930. var mesh = subMesh.getMesh();
  79931. // Render this.mesh as default
  79932. if (mesh === this.mesh && mesh.material) {
  79933. return mesh.material.isReady(mesh);
  79934. }
  79935. var defines = [];
  79936. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79937. var material = subMesh.getMaterial();
  79938. // Alpha test
  79939. if (material) {
  79940. if (material.needAlphaTesting()) {
  79941. defines.push("#define ALPHATEST");
  79942. }
  79943. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79944. attribs.push(BABYLON.VertexBuffer.UVKind);
  79945. defines.push("#define UV1");
  79946. }
  79947. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79948. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79949. defines.push("#define UV2");
  79950. }
  79951. }
  79952. // Bones
  79953. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79954. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79955. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79956. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79957. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79958. }
  79959. else {
  79960. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79961. }
  79962. // Instances
  79963. if (useInstances) {
  79964. defines.push("#define INSTANCES");
  79965. attribs.push("world0");
  79966. attribs.push("world1");
  79967. attribs.push("world2");
  79968. attribs.push("world3");
  79969. }
  79970. // Get correct effect
  79971. var join = defines.join("\n");
  79972. if (this._cachedDefines !== join) {
  79973. this._cachedDefines = join;
  79974. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  79975. }
  79976. return this._volumetricLightScatteringPass.isReady();
  79977. };
  79978. /**
  79979. * Sets the new light position for light scattering effect
  79980. * @param {BABYLON.Vector3} The new custom light position
  79981. */
  79982. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  79983. this.customMeshPosition = position;
  79984. };
  79985. /**
  79986. * Returns the light position for light scattering effect
  79987. * @return {BABYLON.Vector3} The custom light position
  79988. */
  79989. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  79990. return this.customMeshPosition;
  79991. };
  79992. /**
  79993. * Disposes the internal assets and detaches the post-process from the camera
  79994. */
  79995. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  79996. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  79997. if (rttIndex !== -1) {
  79998. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  79999. }
  80000. this._volumetricLightScatteringRTT.dispose();
  80001. _super.prototype.dispose.call(this, camera);
  80002. };
  80003. /**
  80004. * Returns the render target texture used by the post-process
  80005. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  80006. */
  80007. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  80008. return this._volumetricLightScatteringRTT;
  80009. };
  80010. // Private methods
  80011. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  80012. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  80013. return true;
  80014. }
  80015. return false;
  80016. };
  80017. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  80018. var _this = this;
  80019. var engine = scene.getEngine();
  80020. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80021. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80022. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80023. this._volumetricLightScatteringRTT.renderList = null;
  80024. this._volumetricLightScatteringRTT.renderParticles = false;
  80025. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  80026. var camera = this.getCamera();
  80027. if (camera) {
  80028. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80029. }
  80030. else {
  80031. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80032. }
  80033. // Custom render function for submeshes
  80034. var renderSubMesh = function (subMesh) {
  80035. var mesh = subMesh.getRenderingMesh();
  80036. if (_this._meshExcluded(mesh)) {
  80037. return;
  80038. }
  80039. var material = subMesh.getMaterial();
  80040. if (!material) {
  80041. return;
  80042. }
  80043. var scene = mesh.getScene();
  80044. var engine = scene.getEngine();
  80045. // Culling
  80046. engine.setState(material.backFaceCulling);
  80047. // Managing instances
  80048. var batch = mesh._getInstancesRenderList(subMesh._id);
  80049. if (batch.mustReturn) {
  80050. return;
  80051. }
  80052. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80053. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  80054. var effect = _this._volumetricLightScatteringPass;
  80055. if (mesh === _this.mesh) {
  80056. if (subMesh.effect) {
  80057. effect = subMesh.effect;
  80058. }
  80059. else {
  80060. effect = material.getEffect();
  80061. }
  80062. }
  80063. engine.enableEffect(effect);
  80064. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  80065. if (mesh === _this.mesh) {
  80066. material.bind(mesh.getWorldMatrix(), mesh);
  80067. }
  80068. else {
  80069. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  80070. // Alpha test
  80071. if (material && material.needAlphaTesting()) {
  80072. var alphaTexture = material.getAlphaTestTexture();
  80073. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  80074. if (alphaTexture) {
  80075. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80076. }
  80077. }
  80078. // Bones
  80079. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80080. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80081. }
  80082. }
  80083. // Draw
  80084. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  80085. }
  80086. };
  80087. // Render target texture callbacks
  80088. var savedSceneClearColor;
  80089. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  80090. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  80091. savedSceneClearColor = scene.clearColor;
  80092. scene.clearColor = sceneClearColor;
  80093. });
  80094. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  80095. scene.clearColor = savedSceneClearColor;
  80096. });
  80097. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80098. var engine = scene.getEngine();
  80099. var index;
  80100. if (depthOnlySubMeshes.length) {
  80101. engine.setColorWrite(false);
  80102. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80103. renderSubMesh(depthOnlySubMeshes.data[index]);
  80104. }
  80105. engine.setColorWrite(true);
  80106. }
  80107. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80108. renderSubMesh(opaqueSubMeshes.data[index]);
  80109. }
  80110. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80111. renderSubMesh(alphaTestSubMeshes.data[index]);
  80112. }
  80113. if (transparentSubMeshes.length) {
  80114. // Sort sub meshes
  80115. for (index = 0; index < transparentSubMeshes.length; index++) {
  80116. var submesh = transparentSubMeshes.data[index];
  80117. var boundingInfo = submesh.getBoundingInfo();
  80118. if (boundingInfo && scene.activeCamera) {
  80119. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  80120. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  80121. }
  80122. }
  80123. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  80124. sortedArray.sort(function (a, b) {
  80125. // Alpha index first
  80126. if (a._alphaIndex > b._alphaIndex) {
  80127. return 1;
  80128. }
  80129. if (a._alphaIndex < b._alphaIndex) {
  80130. return -1;
  80131. }
  80132. // Then distance to camera
  80133. if (a._distanceToCamera < b._distanceToCamera) {
  80134. return 1;
  80135. }
  80136. if (a._distanceToCamera > b._distanceToCamera) {
  80137. return -1;
  80138. }
  80139. return 0;
  80140. });
  80141. // Render sub meshes
  80142. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  80143. for (index = 0; index < sortedArray.length; index++) {
  80144. renderSubMesh(sortedArray[index]);
  80145. }
  80146. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80147. }
  80148. };
  80149. };
  80150. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  80151. var transform = scene.getTransformMatrix();
  80152. var meshPosition;
  80153. if (this.useCustomMeshPosition) {
  80154. meshPosition = this.customMeshPosition;
  80155. }
  80156. else if (this.attachedNode) {
  80157. meshPosition = this.attachedNode.position;
  80158. }
  80159. else {
  80160. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  80161. }
  80162. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  80163. this._screenCoordinates.x = pos.x / this._viewPort.width;
  80164. this._screenCoordinates.y = pos.y / this._viewPort.height;
  80165. if (this.invert)
  80166. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  80167. };
  80168. // Static methods
  80169. /**
  80170. * Creates a default mesh for the Volumeric Light Scattering post-process
  80171. * @param {string} The mesh name
  80172. * @param {BABYLON.Scene} The scene where to create the mesh
  80173. * @return {BABYLON.Mesh} the default mesh
  80174. */
  80175. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  80176. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  80177. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  80178. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  80179. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  80180. mesh.material = material;
  80181. return mesh;
  80182. };
  80183. __decorate([
  80184. BABYLON.serializeAsVector3()
  80185. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  80186. __decorate([
  80187. BABYLON.serialize()
  80188. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  80189. __decorate([
  80190. BABYLON.serialize()
  80191. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  80192. __decorate([
  80193. BABYLON.serializeAsMeshReference()
  80194. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  80195. __decorate([
  80196. BABYLON.serialize()
  80197. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  80198. __decorate([
  80199. BABYLON.serialize()
  80200. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  80201. __decorate([
  80202. BABYLON.serialize()
  80203. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  80204. __decorate([
  80205. BABYLON.serialize()
  80206. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  80207. __decorate([
  80208. BABYLON.serialize()
  80209. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  80210. return VolumetricLightScatteringPostProcess;
  80211. }(BABYLON.PostProcess));
  80212. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  80213. })(BABYLON || (BABYLON = {}));
  80214. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  80215. //
  80216. // This post-process allows the modification of rendered colors by using
  80217. // a 'look-up table' (LUT). This effect is also called Color Grading.
  80218. //
  80219. // The object needs to be provided an url to a texture containing the color
  80220. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  80221. // Use an image editing software to tweak the LUT to match your needs.
  80222. //
  80223. // For an example of a color LUT, see here:
  80224. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  80225. // For explanations on color grading, see here:
  80226. // http://udn.epicgames.com/Three/ColorGrading.html
  80227. //
  80228. var BABYLON;
  80229. (function (BABYLON) {
  80230. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  80231. __extends(ColorCorrectionPostProcess, _super);
  80232. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  80233. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  80234. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80235. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  80236. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80237. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80238. _this.onApply = function (effect) {
  80239. effect.setTexture("colorTable", _this._colorTableTexture);
  80240. };
  80241. return _this;
  80242. }
  80243. return ColorCorrectionPostProcess;
  80244. }(BABYLON.PostProcess));
  80245. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  80246. })(BABYLON || (BABYLON = {}));
  80247. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  80248. var BABYLON;
  80249. (function (BABYLON) {
  80250. /** Defines operator used for tonemapping */
  80251. var TonemappingOperator;
  80252. (function (TonemappingOperator) {
  80253. /** Hable */
  80254. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  80255. /** Reinhard */
  80256. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  80257. /** HejiDawson */
  80258. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  80259. /** Photographic */
  80260. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  80261. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  80262. ;
  80263. /**
  80264. * Defines a post process to apply tone mapping
  80265. */
  80266. var TonemapPostProcess = /** @class */ (function (_super) {
  80267. __extends(TonemapPostProcess, _super);
  80268. /**
  80269. * Creates a new TonemapPostProcess
  80270. * @param name defines the name of the postprocess
  80271. * @param _operator defines the operator to use
  80272. * @param exposureAdjustment defines the required exposure adjustement
  80273. * @param camera defines the camera to use (can be null)
  80274. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  80275. * @param engine defines the hosting engine (can be ignore if camera is set)
  80276. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  80277. */
  80278. function TonemapPostProcess(name, _operator,
  80279. /** Defines the required exposure adjustement */
  80280. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  80281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80282. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80283. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  80284. _this._operator = _operator;
  80285. _this.exposureAdjustment = exposureAdjustment;
  80286. var defines = "#define ";
  80287. if (_this._operator === TonemappingOperator.Hable)
  80288. defines += "HABLE_TONEMAPPING";
  80289. else if (_this._operator === TonemappingOperator.Reinhard)
  80290. defines += "REINHARD_TONEMAPPING";
  80291. else if (_this._operator === TonemappingOperator.HejiDawson)
  80292. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  80293. else if (_this._operator === TonemappingOperator.Photographic)
  80294. defines += "PHOTOGRAPHIC_TONEMAPPING";
  80295. //sadly a second call to create the effect.
  80296. _this.updateEffect(defines);
  80297. _this.onApply = function (effect) {
  80298. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  80299. };
  80300. return _this;
  80301. }
  80302. return TonemapPostProcess;
  80303. }(BABYLON.PostProcess));
  80304. BABYLON.TonemapPostProcess = TonemapPostProcess;
  80305. })(BABYLON || (BABYLON = {}));
  80306. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  80307. var BABYLON;
  80308. (function (BABYLON) {
  80309. var DisplayPassPostProcess = /** @class */ (function (_super) {
  80310. __extends(DisplayPassPostProcess, _super);
  80311. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  80312. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  80313. }
  80314. return DisplayPassPostProcess;
  80315. }(BABYLON.PostProcess));
  80316. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  80317. })(BABYLON || (BABYLON = {}));
  80318. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  80319. var BABYLON;
  80320. (function (BABYLON) {
  80321. var HighlightsPostProcess = /** @class */ (function (_super) {
  80322. __extends(HighlightsPostProcess, _super);
  80323. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80324. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80325. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80326. }
  80327. return HighlightsPostProcess;
  80328. }(BABYLON.PostProcess));
  80329. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  80330. })(BABYLON || (BABYLON = {}));
  80331. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  80332. var BABYLON;
  80333. (function (BABYLON) {
  80334. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  80335. __extends(ImageProcessingPostProcess, _super);
  80336. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  80337. if (camera === void 0) { camera = null; }
  80338. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80339. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  80340. _this._fromLinearSpace = true;
  80341. /**
  80342. * Defines cache preventing GC.
  80343. */
  80344. _this._defines = {
  80345. IMAGEPROCESSING: false,
  80346. VIGNETTE: false,
  80347. VIGNETTEBLENDMODEMULTIPLY: false,
  80348. VIGNETTEBLENDMODEOPAQUE: false,
  80349. TONEMAPPING: false,
  80350. CONTRAST: false,
  80351. COLORCURVES: false,
  80352. COLORGRADING: false,
  80353. COLORGRADING3D: false,
  80354. FROMLINEARSPACE: false,
  80355. SAMPLER3DGREENDEPTH: false,
  80356. SAMPLER3DBGRMAP: false,
  80357. IMAGEPROCESSINGPOSTPROCESS: false,
  80358. EXPOSURE: false,
  80359. };
  80360. // Setup the configuration as forced by the constructor. This would then not force the
  80361. // scene materials output in linear space and let untouched the default forward pass.
  80362. if (imageProcessingConfiguration) {
  80363. imageProcessingConfiguration.applyByPostProcess = true;
  80364. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  80365. // This will cause the shader to be compiled
  80366. _this.fromLinearSpace = false;
  80367. }
  80368. // Setup the default processing configuration to the scene.
  80369. else {
  80370. _this._attachImageProcessingConfiguration(null, true);
  80371. _this.imageProcessingConfiguration.applyByPostProcess = true;
  80372. }
  80373. _this.onApply = function (effect) {
  80374. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  80375. };
  80376. return _this;
  80377. }
  80378. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  80379. /**
  80380. * Gets the image processing configuration used either in this material.
  80381. */
  80382. get: function () {
  80383. return this._imageProcessingConfiguration;
  80384. },
  80385. /**
  80386. * Sets the Default image processing configuration used either in the this material.
  80387. *
  80388. * If sets to null, the scene one is in use.
  80389. */
  80390. set: function (value) {
  80391. this._attachImageProcessingConfiguration(value);
  80392. },
  80393. enumerable: true,
  80394. configurable: true
  80395. });
  80396. /**
  80397. * Attaches a new image processing configuration to the PBR Material.
  80398. * @param configuration
  80399. */
  80400. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  80401. var _this = this;
  80402. if (doNotBuild === void 0) { doNotBuild = false; }
  80403. if (configuration === this._imageProcessingConfiguration) {
  80404. return;
  80405. }
  80406. // Detaches observer.
  80407. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80408. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80409. }
  80410. // Pick the scene configuration if needed.
  80411. if (!configuration) {
  80412. var scene = null;
  80413. var engine = this.getEngine();
  80414. var camera = this.getCamera();
  80415. if (camera) {
  80416. scene = camera.getScene();
  80417. }
  80418. else if (engine && engine.scenes) {
  80419. var scenes = engine.scenes;
  80420. scene = scenes[scenes.length - 1];
  80421. }
  80422. else {
  80423. scene = BABYLON.Engine.LastCreatedScene;
  80424. }
  80425. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  80426. }
  80427. else {
  80428. this._imageProcessingConfiguration = configuration;
  80429. }
  80430. // Attaches observer.
  80431. if (this._imageProcessingConfiguration) {
  80432. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80433. _this._updateParameters();
  80434. });
  80435. }
  80436. // Ensure the effect will be rebuilt.
  80437. if (!doNotBuild) {
  80438. this._updateParameters();
  80439. }
  80440. };
  80441. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  80442. /**
  80443. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80444. */
  80445. get: function () {
  80446. return this.imageProcessingConfiguration.colorCurves;
  80447. },
  80448. /**
  80449. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80450. */
  80451. set: function (value) {
  80452. this.imageProcessingConfiguration.colorCurves = value;
  80453. },
  80454. enumerable: true,
  80455. configurable: true
  80456. });
  80457. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  80458. /**
  80459. * Gets wether the color curves effect is enabled.
  80460. */
  80461. get: function () {
  80462. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80463. },
  80464. /**
  80465. * Sets wether the color curves effect is enabled.
  80466. */
  80467. set: function (value) {
  80468. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80469. },
  80470. enumerable: true,
  80471. configurable: true
  80472. });
  80473. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  80474. /**
  80475. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80476. */
  80477. get: function () {
  80478. return this.imageProcessingConfiguration.colorGradingTexture;
  80479. },
  80480. /**
  80481. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80482. */
  80483. set: function (value) {
  80484. this.imageProcessingConfiguration.colorGradingTexture = value;
  80485. },
  80486. enumerable: true,
  80487. configurable: true
  80488. });
  80489. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  80490. /**
  80491. * Gets wether the color grading effect is enabled.
  80492. */
  80493. get: function () {
  80494. return this.imageProcessingConfiguration.colorGradingEnabled;
  80495. },
  80496. /**
  80497. * Gets wether the color grading effect is enabled.
  80498. */
  80499. set: function (value) {
  80500. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80501. },
  80502. enumerable: true,
  80503. configurable: true
  80504. });
  80505. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  80506. /**
  80507. * Gets exposure used in the effect.
  80508. */
  80509. get: function () {
  80510. return this.imageProcessingConfiguration.exposure;
  80511. },
  80512. /**
  80513. * Sets exposure used in the effect.
  80514. */
  80515. set: function (value) {
  80516. this.imageProcessingConfiguration.exposure = value;
  80517. },
  80518. enumerable: true,
  80519. configurable: true
  80520. });
  80521. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  80522. /**
  80523. * Gets wether tonemapping is enabled or not.
  80524. */
  80525. get: function () {
  80526. return this._imageProcessingConfiguration.toneMappingEnabled;
  80527. },
  80528. /**
  80529. * Sets wether tonemapping is enabled or not
  80530. */
  80531. set: function (value) {
  80532. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80533. },
  80534. enumerable: true,
  80535. configurable: true
  80536. });
  80537. ;
  80538. ;
  80539. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  80540. /**
  80541. * Gets contrast used in the effect.
  80542. */
  80543. get: function () {
  80544. return this.imageProcessingConfiguration.contrast;
  80545. },
  80546. /**
  80547. * Sets contrast used in the effect.
  80548. */
  80549. set: function (value) {
  80550. this.imageProcessingConfiguration.contrast = value;
  80551. },
  80552. enumerable: true,
  80553. configurable: true
  80554. });
  80555. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  80556. /**
  80557. * Gets Vignette stretch size.
  80558. */
  80559. get: function () {
  80560. return this.imageProcessingConfiguration.vignetteStretch;
  80561. },
  80562. /**
  80563. * Sets Vignette stretch size.
  80564. */
  80565. set: function (value) {
  80566. this.imageProcessingConfiguration.vignetteStretch = value;
  80567. },
  80568. enumerable: true,
  80569. configurable: true
  80570. });
  80571. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  80572. /**
  80573. * Gets Vignette centre X Offset.
  80574. */
  80575. get: function () {
  80576. return this.imageProcessingConfiguration.vignetteCentreX;
  80577. },
  80578. /**
  80579. * Sets Vignette centre X Offset.
  80580. */
  80581. set: function (value) {
  80582. this.imageProcessingConfiguration.vignetteCentreX = value;
  80583. },
  80584. enumerable: true,
  80585. configurable: true
  80586. });
  80587. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  80588. /**
  80589. * Gets Vignette centre Y Offset.
  80590. */
  80591. get: function () {
  80592. return this.imageProcessingConfiguration.vignetteCentreY;
  80593. },
  80594. /**
  80595. * Sets Vignette centre Y Offset.
  80596. */
  80597. set: function (value) {
  80598. this.imageProcessingConfiguration.vignetteCentreY = value;
  80599. },
  80600. enumerable: true,
  80601. configurable: true
  80602. });
  80603. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  80604. /**
  80605. * Gets Vignette weight or intensity of the vignette effect.
  80606. */
  80607. get: function () {
  80608. return this.imageProcessingConfiguration.vignetteWeight;
  80609. },
  80610. /**
  80611. * Sets Vignette weight or intensity of the vignette effect.
  80612. */
  80613. set: function (value) {
  80614. this.imageProcessingConfiguration.vignetteWeight = value;
  80615. },
  80616. enumerable: true,
  80617. configurable: true
  80618. });
  80619. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  80620. /**
  80621. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80622. * if vignetteEnabled is set to true.
  80623. */
  80624. get: function () {
  80625. return this.imageProcessingConfiguration.vignetteColor;
  80626. },
  80627. /**
  80628. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80629. * if vignetteEnabled is set to true.
  80630. */
  80631. set: function (value) {
  80632. this.imageProcessingConfiguration.vignetteColor = value;
  80633. },
  80634. enumerable: true,
  80635. configurable: true
  80636. });
  80637. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  80638. /**
  80639. * Gets Camera field of view used by the Vignette effect.
  80640. */
  80641. get: function () {
  80642. return this.imageProcessingConfiguration.vignetteCameraFov;
  80643. },
  80644. /**
  80645. * Sets Camera field of view used by the Vignette effect.
  80646. */
  80647. set: function (value) {
  80648. this.imageProcessingConfiguration.vignetteCameraFov = value;
  80649. },
  80650. enumerable: true,
  80651. configurable: true
  80652. });
  80653. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  80654. /**
  80655. * Gets the vignette blend mode allowing different kind of effect.
  80656. */
  80657. get: function () {
  80658. return this.imageProcessingConfiguration.vignetteBlendMode;
  80659. },
  80660. /**
  80661. * Sets the vignette blend mode allowing different kind of effect.
  80662. */
  80663. set: function (value) {
  80664. this.imageProcessingConfiguration.vignetteBlendMode = value;
  80665. },
  80666. enumerable: true,
  80667. configurable: true
  80668. });
  80669. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  80670. /**
  80671. * Gets wether the vignette effect is enabled.
  80672. */
  80673. get: function () {
  80674. return this.imageProcessingConfiguration.vignetteEnabled;
  80675. },
  80676. /**
  80677. * Sets wether the vignette effect is enabled.
  80678. */
  80679. set: function (value) {
  80680. this.imageProcessingConfiguration.vignetteEnabled = value;
  80681. },
  80682. enumerable: true,
  80683. configurable: true
  80684. });
  80685. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  80686. /**
  80687. * Gets wether the input of the processing is in Gamma or Linear Space.
  80688. */
  80689. get: function () {
  80690. return this._fromLinearSpace;
  80691. },
  80692. /**
  80693. * Sets wether the input of the processing is in Gamma or Linear Space.
  80694. */
  80695. set: function (value) {
  80696. if (this._fromLinearSpace === value) {
  80697. return;
  80698. }
  80699. this._fromLinearSpace = value;
  80700. this._updateParameters();
  80701. },
  80702. enumerable: true,
  80703. configurable: true
  80704. });
  80705. ImageProcessingPostProcess.prototype.getClassName = function () {
  80706. return "ImageProcessingPostProcess";
  80707. };
  80708. ImageProcessingPostProcess.prototype._updateParameters = function () {
  80709. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  80710. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  80711. var defines = "";
  80712. for (var define in this._defines) {
  80713. if (this._defines[define]) {
  80714. defines += "#define " + define + ";\r\n";
  80715. }
  80716. }
  80717. var samplers = ["textureSampler"];
  80718. var uniforms = ["scale"];
  80719. if (BABYLON.ImageProcessingConfiguration) {
  80720. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  80721. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  80722. }
  80723. this.updateEffect(defines, uniforms, samplers);
  80724. };
  80725. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  80726. _super.prototype.dispose.call(this, camera);
  80727. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80728. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80729. }
  80730. if (this._imageProcessingConfiguration) {
  80731. this.imageProcessingConfiguration.applyByPostProcess = false;
  80732. }
  80733. };
  80734. __decorate([
  80735. BABYLON.serialize()
  80736. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  80737. return ImageProcessingPostProcess;
  80738. }(BABYLON.PostProcess));
  80739. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  80740. })(BABYLON || (BABYLON = {}));
  80741. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  80742. var BABYLON;
  80743. (function (BABYLON) {
  80744. /**
  80745. * Class used to store bone information
  80746. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80747. */
  80748. var Bone = /** @class */ (function (_super) {
  80749. __extends(Bone, _super);
  80750. /**
  80751. * Create a new bone
  80752. * @param name defines the bone name
  80753. * @param skeleton defines the parent skeleton
  80754. * @param parentBone defines the parent (can be null if the bone is the root)
  80755. * @param localMatrix defines the local matrix
  80756. * @param restPose defines the rest pose matrix
  80757. * @param baseMatrix defines the base matrix
  80758. * @param index defines index of the bone in the hiearchy
  80759. */
  80760. function Bone(
  80761. /**
  80762. * defines the bone name
  80763. */
  80764. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  80765. if (parentBone === void 0) { parentBone = null; }
  80766. if (localMatrix === void 0) { localMatrix = null; }
  80767. if (restPose === void 0) { restPose = null; }
  80768. if (baseMatrix === void 0) { baseMatrix = null; }
  80769. if (index === void 0) { index = null; }
  80770. var _this = _super.call(this, name, skeleton.getScene()) || this;
  80771. _this.name = name;
  80772. /**
  80773. * Gets the list of child bones
  80774. */
  80775. _this.children = new Array();
  80776. /** Gets the animations associated with this bone */
  80777. _this.animations = new Array();
  80778. /**
  80779. * @hidden Internal only
  80780. * Set this value to map this bone to a different index in the transform matrices
  80781. * Set this value to -1 to exclude the bone from the transform matrices
  80782. */
  80783. _this._index = null;
  80784. _this._absoluteTransform = new BABYLON.Matrix();
  80785. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  80786. _this._scalingDeterminant = 1;
  80787. _this._worldTransform = new BABYLON.Matrix();
  80788. _this._needToDecompose = true;
  80789. _this._needToCompose = false;
  80790. _this._skeleton = skeleton;
  80791. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  80792. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  80793. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  80794. _this._index = index;
  80795. skeleton.bones.push(_this);
  80796. _this.setParent(parentBone, false);
  80797. if (baseMatrix || localMatrix) {
  80798. _this._updateDifferenceMatrix();
  80799. }
  80800. return _this;
  80801. }
  80802. Object.defineProperty(Bone.prototype, "_matrix", {
  80803. /** @hidden */
  80804. get: function () {
  80805. this._compose();
  80806. return this._localMatrix;
  80807. },
  80808. /** @hidden */
  80809. set: function (value) {
  80810. this._localMatrix.copyFrom(value);
  80811. this._needToDecompose = true;
  80812. },
  80813. enumerable: true,
  80814. configurable: true
  80815. });
  80816. // Members
  80817. /**
  80818. * Gets the parent skeleton
  80819. * @returns a skeleton
  80820. */
  80821. Bone.prototype.getSkeleton = function () {
  80822. return this._skeleton;
  80823. };
  80824. /**
  80825. * Gets parent bone
  80826. * @returns a bone or null if the bone is the root of the bone hierarchy
  80827. */
  80828. Bone.prototype.getParent = function () {
  80829. return this._parent;
  80830. };
  80831. /**
  80832. * Sets the parent bone
  80833. * @param parent defines the parent (can be null if the bone is the root)
  80834. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80835. */
  80836. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  80837. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80838. if (this._parent === parent) {
  80839. return;
  80840. }
  80841. if (this._parent) {
  80842. var index = this._parent.children.indexOf(this);
  80843. if (index !== -1) {
  80844. this._parent.children.splice(index, 1);
  80845. }
  80846. }
  80847. this._parent = parent;
  80848. if (this._parent) {
  80849. this._parent.children.push(this);
  80850. }
  80851. if (updateDifferenceMatrix) {
  80852. this._updateDifferenceMatrix();
  80853. }
  80854. this.markAsDirty();
  80855. };
  80856. /**
  80857. * Gets the local matrix
  80858. * @returns a matrix
  80859. */
  80860. Bone.prototype.getLocalMatrix = function () {
  80861. this._compose();
  80862. return this._localMatrix;
  80863. };
  80864. /**
  80865. * Gets the base matrix (initial matrix which remains unchanged)
  80866. * @returns a matrix
  80867. */
  80868. Bone.prototype.getBaseMatrix = function () {
  80869. return this._baseMatrix;
  80870. };
  80871. /**
  80872. * Gets the rest pose matrix
  80873. * @returns a matrix
  80874. */
  80875. Bone.prototype.getRestPose = function () {
  80876. return this._restPose;
  80877. };
  80878. /**
  80879. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  80880. */
  80881. Bone.prototype.getWorldMatrix = function () {
  80882. return this._worldTransform;
  80883. };
  80884. /**
  80885. * Sets the local matrix to rest pose matrix
  80886. */
  80887. Bone.prototype.returnToRest = function () {
  80888. this.updateMatrix(this._restPose.clone());
  80889. };
  80890. /**
  80891. * Gets the inverse of the absolute transform matrix.
  80892. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  80893. * @returns a matrix
  80894. */
  80895. Bone.prototype.getInvertedAbsoluteTransform = function () {
  80896. return this._invertedAbsoluteTransform;
  80897. };
  80898. /**
  80899. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  80900. * @returns a matrix
  80901. */
  80902. Bone.prototype.getAbsoluteTransform = function () {
  80903. return this._absoluteTransform;
  80904. };
  80905. Object.defineProperty(Bone.prototype, "position", {
  80906. // Properties (matches AbstractMesh properties)
  80907. /** Gets or sets current position (in local space) */
  80908. get: function () {
  80909. this._decompose();
  80910. return this._localPosition;
  80911. },
  80912. set: function (newPosition) {
  80913. this._decompose();
  80914. this._localPosition.copyFrom(newPosition);
  80915. this._markAsDirtyAndCompose();
  80916. },
  80917. enumerable: true,
  80918. configurable: true
  80919. });
  80920. Object.defineProperty(Bone.prototype, "rotation", {
  80921. /** Gets or sets current rotation (in local space) */
  80922. get: function () {
  80923. return this.getRotation();
  80924. },
  80925. set: function (newRotation) {
  80926. this.setRotation(newRotation);
  80927. },
  80928. enumerable: true,
  80929. configurable: true
  80930. });
  80931. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  80932. /** Gets or sets current rotation quaternion (in local space) */
  80933. get: function () {
  80934. this._decompose();
  80935. return this._localRotation;
  80936. },
  80937. set: function (newRotation) {
  80938. this.setRotationQuaternion(newRotation);
  80939. },
  80940. enumerable: true,
  80941. configurable: true
  80942. });
  80943. Object.defineProperty(Bone.prototype, "scaling", {
  80944. /** Gets or sets current scaling (in local space) */
  80945. get: function () {
  80946. return this.getScale();
  80947. },
  80948. set: function (newScaling) {
  80949. this.setScale(newScaling);
  80950. },
  80951. enumerable: true,
  80952. configurable: true
  80953. });
  80954. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  80955. /**
  80956. * Gets the animation properties override
  80957. */
  80958. get: function () {
  80959. return this._skeleton.animationPropertiesOverride;
  80960. },
  80961. enumerable: true,
  80962. configurable: true
  80963. });
  80964. // Methods
  80965. Bone.prototype._decompose = function () {
  80966. if (!this._needToDecompose) {
  80967. return;
  80968. }
  80969. this._needToDecompose = false;
  80970. if (!this._localScaling) {
  80971. this._localScaling = BABYLON.Vector3.Zero();
  80972. this._localRotation = BABYLON.Quaternion.Zero();
  80973. this._localPosition = BABYLON.Vector3.Zero();
  80974. }
  80975. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  80976. };
  80977. Bone.prototype._compose = function () {
  80978. if (!this._needToCompose) {
  80979. return;
  80980. }
  80981. this._needToCompose = false;
  80982. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  80983. };
  80984. /**
  80985. * Update the base and local matrices
  80986. * @param matrix defines the new base or local matrix
  80987. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80988. * @param updateLocalMatrix defines if the local matrix should be updated
  80989. */
  80990. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  80991. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80992. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  80993. this._baseMatrix.copyFrom(matrix);
  80994. if (updateDifferenceMatrix) {
  80995. this._updateDifferenceMatrix();
  80996. }
  80997. if (updateLocalMatrix) {
  80998. this._localMatrix.copyFrom(matrix);
  80999. this._markAsDirtyAndDecompose();
  81000. }
  81001. else {
  81002. this.markAsDirty();
  81003. }
  81004. };
  81005. /** @hidden */
  81006. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  81007. if (updateChildren === void 0) { updateChildren = true; }
  81008. if (!rootMatrix) {
  81009. rootMatrix = this._baseMatrix;
  81010. }
  81011. if (this._parent) {
  81012. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81013. }
  81014. else {
  81015. this._absoluteTransform.copyFrom(rootMatrix);
  81016. }
  81017. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  81018. if (updateChildren) {
  81019. for (var index = 0; index < this.children.length; index++) {
  81020. this.children[index]._updateDifferenceMatrix();
  81021. }
  81022. }
  81023. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  81024. };
  81025. /**
  81026. * Flag the bone as dirty (Forcing it to update everything)
  81027. */
  81028. Bone.prototype.markAsDirty = function () {
  81029. this._currentRenderId++;
  81030. this._childRenderId++;
  81031. this._skeleton._markAsDirty();
  81032. };
  81033. Bone.prototype._markAsDirtyAndCompose = function () {
  81034. this.markAsDirty();
  81035. this._needToCompose = true;
  81036. };
  81037. Bone.prototype._markAsDirtyAndDecompose = function () {
  81038. this.markAsDirty();
  81039. this._needToDecompose = true;
  81040. };
  81041. /**
  81042. * Copy an animation range from another bone
  81043. * @param source defines the source bone
  81044. * @param rangeName defines the range name to copy
  81045. * @param frameOffset defines the frame offset
  81046. * @param rescaleAsRequired defines if rescaling must be applied if required
  81047. * @param skelDimensionsRatio defines the scaling ratio
  81048. * @returns true if operation was successful
  81049. */
  81050. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  81051. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81052. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  81053. // all animation may be coming from a library skeleton, so may need to create animation
  81054. if (this.animations.length === 0) {
  81055. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  81056. this.animations[0].setKeys([]);
  81057. }
  81058. // get animation info / verify there is such a range from the source bone
  81059. var sourceRange = source.animations[0].getRange(rangeName);
  81060. if (!sourceRange) {
  81061. return false;
  81062. }
  81063. var from = sourceRange.from;
  81064. var to = sourceRange.to;
  81065. var sourceKeys = source.animations[0].getKeys();
  81066. // rescaling prep
  81067. var sourceBoneLength = source.length;
  81068. var sourceParent = source.getParent();
  81069. var parent = this.getParent();
  81070. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  81071. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  81072. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  81073. var destKeys = this.animations[0].getKeys();
  81074. // loop vars declaration
  81075. var orig;
  81076. var origTranslation;
  81077. var mat;
  81078. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  81079. orig = sourceKeys[key];
  81080. if (orig.frame >= from && orig.frame <= to) {
  81081. if (rescaleAsRequired) {
  81082. mat = orig.value.clone();
  81083. // scale based on parent ratio, when bone has parent
  81084. if (parentScalingReqd) {
  81085. origTranslation = mat.getTranslation();
  81086. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  81087. // scale based on skeleton dimension ratio when root bone, and value is passed
  81088. }
  81089. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  81090. origTranslation = mat.getTranslation();
  81091. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  81092. // use original when root bone, and no data for skelDimensionsRatio
  81093. }
  81094. else {
  81095. mat = orig.value;
  81096. }
  81097. }
  81098. else {
  81099. mat = orig.value;
  81100. }
  81101. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  81102. }
  81103. }
  81104. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  81105. return true;
  81106. };
  81107. /**
  81108. * Translate the bone in local or world space
  81109. * @param vec The amount to translate the bone
  81110. * @param space The space that the translation is in
  81111. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81112. */
  81113. Bone.prototype.translate = function (vec, space, mesh) {
  81114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81115. var lm = this.getLocalMatrix();
  81116. if (space == BABYLON.Space.LOCAL) {
  81117. lm.m[12] += vec.x;
  81118. lm.m[13] += vec.y;
  81119. lm.m[14] += vec.z;
  81120. }
  81121. else {
  81122. var wm = null;
  81123. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81124. if (mesh) {
  81125. wm = mesh.getWorldMatrix();
  81126. }
  81127. this._skeleton.computeAbsoluteTransforms();
  81128. var tmat = Bone._tmpMats[0];
  81129. var tvec = Bone._tmpVecs[0];
  81130. if (this._parent) {
  81131. if (mesh && wm) {
  81132. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81133. tmat.multiplyToRef(wm, tmat);
  81134. }
  81135. else {
  81136. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81137. }
  81138. }
  81139. tmat.m[12] = 0;
  81140. tmat.m[13] = 0;
  81141. tmat.m[14] = 0;
  81142. tmat.invert();
  81143. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  81144. lm.m[12] += tvec.x;
  81145. lm.m[13] += tvec.y;
  81146. lm.m[14] += tvec.z;
  81147. }
  81148. this._markAsDirtyAndDecompose();
  81149. };
  81150. /**
  81151. * Set the postion of the bone in local or world space
  81152. * @param position The position to set the bone
  81153. * @param space The space that the position is in
  81154. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81155. */
  81156. Bone.prototype.setPosition = function (position, space, mesh) {
  81157. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81158. var lm = this.getLocalMatrix();
  81159. if (space == BABYLON.Space.LOCAL) {
  81160. lm.m[12] = position.x;
  81161. lm.m[13] = position.y;
  81162. lm.m[14] = position.z;
  81163. }
  81164. else {
  81165. var wm = null;
  81166. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81167. if (mesh) {
  81168. wm = mesh.getWorldMatrix();
  81169. }
  81170. this._skeleton.computeAbsoluteTransforms();
  81171. var tmat = Bone._tmpMats[0];
  81172. var vec = Bone._tmpVecs[0];
  81173. if (this._parent) {
  81174. if (mesh && wm) {
  81175. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81176. tmat.multiplyToRef(wm, tmat);
  81177. }
  81178. else {
  81179. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81180. }
  81181. }
  81182. tmat.invert();
  81183. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  81184. lm.m[12] = vec.x;
  81185. lm.m[13] = vec.y;
  81186. lm.m[14] = vec.z;
  81187. }
  81188. this._markAsDirtyAndDecompose();
  81189. };
  81190. /**
  81191. * Set the absolute position of the bone (world space)
  81192. * @param position The position to set the bone
  81193. * @param mesh The mesh that this bone is attached to
  81194. */
  81195. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  81196. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  81197. };
  81198. /**
  81199. * Scale the bone on the x, y and z axes (in local space)
  81200. * @param x The amount to scale the bone on the x axis
  81201. * @param y The amount to scale the bone on the y axis
  81202. * @param z The amount to scale the bone on the z axis
  81203. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  81204. */
  81205. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  81206. if (scaleChildren === void 0) { scaleChildren = false; }
  81207. var locMat = this.getLocalMatrix();
  81208. // Apply new scaling on top of current local matrix
  81209. var scaleMat = Bone._tmpMats[0];
  81210. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  81211. scaleMat.multiplyToRef(locMat, locMat);
  81212. // Invert scaling matrix and apply the inverse to all children
  81213. scaleMat.invert();
  81214. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  81215. var child = _a[_i];
  81216. var cm = child.getLocalMatrix();
  81217. cm.multiplyToRef(scaleMat, cm);
  81218. cm.m[12] *= x;
  81219. cm.m[13] *= y;
  81220. cm.m[14] *= z;
  81221. child._markAsDirtyAndDecompose();
  81222. }
  81223. this._markAsDirtyAndDecompose();
  81224. if (scaleChildren) {
  81225. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  81226. var child = _c[_b];
  81227. child.scale(x, y, z, scaleChildren);
  81228. }
  81229. }
  81230. };
  81231. /**
  81232. * Set the bone scaling in local space
  81233. * @param scale defines the scaling vector
  81234. */
  81235. Bone.prototype.setScale = function (scale) {
  81236. this._decompose();
  81237. this._localScaling.copyFrom(scale);
  81238. this._markAsDirtyAndCompose();
  81239. };
  81240. /**
  81241. * Gets the current scaling in local space
  81242. * @returns the current scaling vector
  81243. */
  81244. Bone.prototype.getScale = function () {
  81245. this._decompose();
  81246. return this._localScaling;
  81247. };
  81248. /**
  81249. * Gets the current scaling in local space and stores it in a target vector
  81250. * @param result defines the target vector
  81251. */
  81252. Bone.prototype.getScaleToRef = function (result) {
  81253. this._decompose();
  81254. result.copyFrom(this._localScaling);
  81255. };
  81256. /**
  81257. * Set the yaw, pitch, and roll of the bone in local or world space
  81258. * @param yaw The rotation of the bone on the y axis
  81259. * @param pitch The rotation of the bone on the x axis
  81260. * @param roll The rotation of the bone on the z axis
  81261. * @param space The space that the axes of rotation are in
  81262. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81263. */
  81264. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  81265. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81266. if (space === BABYLON.Space.LOCAL) {
  81267. var quat = Bone._tmpQuat;
  81268. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  81269. this.setRotationQuaternion(quat, space, mesh);
  81270. return;
  81271. }
  81272. var rotMatInv = Bone._tmpMats[0];
  81273. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81274. return;
  81275. }
  81276. var rotMat = Bone._tmpMats[1];
  81277. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  81278. rotMatInv.multiplyToRef(rotMat, rotMat);
  81279. this._rotateWithMatrix(rotMat, space, mesh);
  81280. };
  81281. /**
  81282. * Add a rotation to the bone on an axis in local or world space
  81283. * @param axis The axis to rotate the bone on
  81284. * @param amount The amount to rotate the bone
  81285. * @param space The space that the axis is in
  81286. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81287. */
  81288. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  81289. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81290. var rmat = Bone._tmpMats[0];
  81291. rmat.m[12] = 0;
  81292. rmat.m[13] = 0;
  81293. rmat.m[14] = 0;
  81294. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  81295. this._rotateWithMatrix(rmat, space, mesh);
  81296. };
  81297. /**
  81298. * Set the rotation of the bone to a particular axis angle in local or world space
  81299. * @param axis The axis to rotate the bone on
  81300. * @param angle The angle that the bone should be rotated to
  81301. * @param space The space that the axis is in
  81302. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81303. */
  81304. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  81305. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81306. if (space === BABYLON.Space.LOCAL) {
  81307. var quat = Bone._tmpQuat;
  81308. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  81309. this.setRotationQuaternion(quat, space, mesh);
  81310. return;
  81311. }
  81312. var rotMatInv = Bone._tmpMats[0];
  81313. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81314. return;
  81315. }
  81316. var rotMat = Bone._tmpMats[1];
  81317. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  81318. rotMatInv.multiplyToRef(rotMat, rotMat);
  81319. this._rotateWithMatrix(rotMat, space, mesh);
  81320. };
  81321. /**
  81322. * Set the euler rotation of the bone in local of world space
  81323. * @param rotation The euler rotation that the bone should be set to
  81324. * @param space The space that the rotation is in
  81325. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81326. */
  81327. Bone.prototype.setRotation = function (rotation, space, mesh) {
  81328. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81329. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  81330. };
  81331. /**
  81332. * Set the quaternion rotation of the bone in local of world space
  81333. * @param quat The quaternion rotation that the bone should be set to
  81334. * @param space The space that the rotation is in
  81335. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81336. */
  81337. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  81338. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81339. if (space === BABYLON.Space.LOCAL) {
  81340. this._decompose();
  81341. this._localRotation.copyFrom(quat);
  81342. this._markAsDirtyAndCompose();
  81343. return;
  81344. }
  81345. var rotMatInv = Bone._tmpMats[0];
  81346. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81347. return;
  81348. }
  81349. var rotMat = Bone._tmpMats[1];
  81350. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  81351. rotMatInv.multiplyToRef(rotMat, rotMat);
  81352. this._rotateWithMatrix(rotMat, space, mesh);
  81353. };
  81354. /**
  81355. * Set the rotation matrix of the bone in local of world space
  81356. * @param rotMat The rotation matrix that the bone should be set to
  81357. * @param space The space that the rotation is in
  81358. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81359. */
  81360. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  81361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81362. if (space === BABYLON.Space.LOCAL) {
  81363. var quat = Bone._tmpQuat;
  81364. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  81365. this.setRotationQuaternion(quat, space, mesh);
  81366. return;
  81367. }
  81368. var rotMatInv = Bone._tmpMats[0];
  81369. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81370. return;
  81371. }
  81372. var rotMat2 = Bone._tmpMats[1];
  81373. rotMat2.copyFrom(rotMat);
  81374. rotMatInv.multiplyToRef(rotMat, rotMat2);
  81375. this._rotateWithMatrix(rotMat2, space, mesh);
  81376. };
  81377. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  81378. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81379. var lmat = this.getLocalMatrix();
  81380. var lx = lmat.m[12];
  81381. var ly = lmat.m[13];
  81382. var lz = lmat.m[14];
  81383. var parent = this.getParent();
  81384. var parentScale = Bone._tmpMats[3];
  81385. var parentScaleInv = Bone._tmpMats[4];
  81386. if (parent && space == BABYLON.Space.WORLD) {
  81387. if (mesh) {
  81388. parentScale.copyFrom(mesh.getWorldMatrix());
  81389. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  81390. }
  81391. else {
  81392. parentScale.copyFrom(parent.getAbsoluteTransform());
  81393. }
  81394. parentScaleInv.copyFrom(parentScale);
  81395. parentScaleInv.invert();
  81396. lmat.multiplyToRef(parentScale, lmat);
  81397. lmat.multiplyToRef(rmat, lmat);
  81398. lmat.multiplyToRef(parentScaleInv, lmat);
  81399. }
  81400. else {
  81401. if (space == BABYLON.Space.WORLD && mesh) {
  81402. parentScale.copyFrom(mesh.getWorldMatrix());
  81403. parentScaleInv.copyFrom(parentScale);
  81404. parentScaleInv.invert();
  81405. lmat.multiplyToRef(parentScale, lmat);
  81406. lmat.multiplyToRef(rmat, lmat);
  81407. lmat.multiplyToRef(parentScaleInv, lmat);
  81408. }
  81409. else {
  81410. lmat.multiplyToRef(rmat, lmat);
  81411. }
  81412. }
  81413. lmat.m[12] = lx;
  81414. lmat.m[13] = ly;
  81415. lmat.m[14] = lz;
  81416. this.computeAbsoluteTransforms();
  81417. this._markAsDirtyAndDecompose();
  81418. };
  81419. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  81420. var scaleMatrix = Bone._tmpMats[2];
  81421. rotMatInv.copyFrom(this.getAbsoluteTransform());
  81422. if (mesh) {
  81423. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  81424. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  81425. }
  81426. rotMatInv.invert();
  81427. if (isNaN(rotMatInv.m[0])) {
  81428. // Matrix failed to invert.
  81429. // This can happen if scale is zero for example.
  81430. return false;
  81431. }
  81432. scaleMatrix.m[0] *= this._scalingDeterminant;
  81433. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  81434. return true;
  81435. };
  81436. /**
  81437. * Get the position of the bone in local or world space
  81438. * @param space The space that the returned position is in
  81439. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81440. * @returns The position of the bone
  81441. */
  81442. Bone.prototype.getPosition = function (space, mesh) {
  81443. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81444. if (mesh === void 0) { mesh = null; }
  81445. var pos = BABYLON.Vector3.Zero();
  81446. this.getPositionToRef(space, mesh, pos);
  81447. return pos;
  81448. };
  81449. /**
  81450. * Copy the position of the bone to a vector3 in local or world space
  81451. * @param space The space that the returned position is in
  81452. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81453. * @param result The vector3 to copy the position to
  81454. */
  81455. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  81456. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81457. if (space == BABYLON.Space.LOCAL) {
  81458. var lm = this.getLocalMatrix();
  81459. result.x = lm.m[12];
  81460. result.y = lm.m[13];
  81461. result.z = lm.m[14];
  81462. }
  81463. else {
  81464. var wm = null;
  81465. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81466. if (mesh) {
  81467. wm = mesh.getWorldMatrix();
  81468. }
  81469. this._skeleton.computeAbsoluteTransforms();
  81470. var tmat = Bone._tmpMats[0];
  81471. if (mesh && wm) {
  81472. tmat.copyFrom(this.getAbsoluteTransform());
  81473. tmat.multiplyToRef(wm, tmat);
  81474. }
  81475. else {
  81476. tmat = this.getAbsoluteTransform();
  81477. }
  81478. result.x = tmat.m[12];
  81479. result.y = tmat.m[13];
  81480. result.z = tmat.m[14];
  81481. }
  81482. };
  81483. /**
  81484. * Get the absolute position of the bone (world space)
  81485. * @param mesh The mesh that this bone is attached to
  81486. * @returns The absolute position of the bone
  81487. */
  81488. Bone.prototype.getAbsolutePosition = function (mesh) {
  81489. if (mesh === void 0) { mesh = null; }
  81490. var pos = BABYLON.Vector3.Zero();
  81491. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  81492. return pos;
  81493. };
  81494. /**
  81495. * Copy the absolute position of the bone (world space) to the result param
  81496. * @param mesh The mesh that this bone is attached to
  81497. * @param result The vector3 to copy the absolute position to
  81498. */
  81499. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  81500. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  81501. };
  81502. /**
  81503. * Compute the absolute transforms of this bone and its children
  81504. */
  81505. Bone.prototype.computeAbsoluteTransforms = function () {
  81506. this._compose();
  81507. if (this._parent) {
  81508. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81509. }
  81510. else {
  81511. this._absoluteTransform.copyFrom(this._localMatrix);
  81512. var poseMatrix = this._skeleton.getPoseMatrix();
  81513. if (poseMatrix) {
  81514. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  81515. }
  81516. }
  81517. var children = this.children;
  81518. var len = children.length;
  81519. for (var i = 0; i < len; i++) {
  81520. children[i].computeAbsoluteTransforms();
  81521. }
  81522. };
  81523. /**
  81524. * Get the world direction from an axis that is in the local space of the bone
  81525. * @param localAxis The local direction that is used to compute the world direction
  81526. * @param mesh The mesh that this bone is attached to
  81527. * @returns The world direction
  81528. */
  81529. Bone.prototype.getDirection = function (localAxis, mesh) {
  81530. if (mesh === void 0) { mesh = null; }
  81531. var result = BABYLON.Vector3.Zero();
  81532. this.getDirectionToRef(localAxis, mesh, result);
  81533. return result;
  81534. };
  81535. /**
  81536. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  81537. * @param localAxis The local direction that is used to compute the world direction
  81538. * @param mesh The mesh that this bone is attached to
  81539. * @param result The vector3 that the world direction will be copied to
  81540. */
  81541. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  81542. if (mesh === void 0) { mesh = null; }
  81543. var wm = null;
  81544. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81545. if (mesh) {
  81546. wm = mesh.getWorldMatrix();
  81547. }
  81548. this._skeleton.computeAbsoluteTransforms();
  81549. var mat = Bone._tmpMats[0];
  81550. mat.copyFrom(this.getAbsoluteTransform());
  81551. if (mesh && wm) {
  81552. mat.multiplyToRef(wm, mat);
  81553. }
  81554. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  81555. result.normalize();
  81556. };
  81557. /**
  81558. * Get the euler rotation of the bone in local or world space
  81559. * @param space The space that the rotation should be in
  81560. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81561. * @returns The euler rotation
  81562. */
  81563. Bone.prototype.getRotation = function (space, mesh) {
  81564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81565. if (mesh === void 0) { mesh = null; }
  81566. var result = BABYLON.Vector3.Zero();
  81567. this.getRotationToRef(space, mesh, result);
  81568. return result;
  81569. };
  81570. /**
  81571. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  81572. * @param space The space that the rotation should be in
  81573. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81574. * @param result The vector3 that the rotation should be copied to
  81575. */
  81576. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  81577. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81578. if (mesh === void 0) { mesh = null; }
  81579. var quat = Bone._tmpQuat;
  81580. this.getRotationQuaternionToRef(space, mesh, quat);
  81581. quat.toEulerAnglesToRef(result);
  81582. };
  81583. /**
  81584. * Get the quaternion rotation of the bone in either local or world space
  81585. * @param space The space that the rotation should be in
  81586. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81587. * @returns The quaternion rotation
  81588. */
  81589. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  81590. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81591. if (mesh === void 0) { mesh = null; }
  81592. var result = BABYLON.Quaternion.Identity();
  81593. this.getRotationQuaternionToRef(space, mesh, result);
  81594. return result;
  81595. };
  81596. /**
  81597. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  81598. * @param space The space that the rotation should be in
  81599. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81600. * @param result The quaternion that the rotation should be copied to
  81601. */
  81602. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  81603. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81604. if (mesh === void 0) { mesh = null; }
  81605. if (space == BABYLON.Space.LOCAL) {
  81606. this._decompose();
  81607. result.copyFrom(this._localRotation);
  81608. }
  81609. else {
  81610. var mat = Bone._tmpMats[0];
  81611. var amat = this.getAbsoluteTransform();
  81612. if (mesh) {
  81613. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81614. }
  81615. else {
  81616. mat.copyFrom(amat);
  81617. }
  81618. mat.m[0] *= this._scalingDeterminant;
  81619. mat.m[1] *= this._scalingDeterminant;
  81620. mat.m[2] *= this._scalingDeterminant;
  81621. mat.decompose(undefined, result, undefined);
  81622. }
  81623. };
  81624. /**
  81625. * Get the rotation matrix of the bone in local or world space
  81626. * @param space The space that the rotation should be in
  81627. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81628. * @returns The rotation matrix
  81629. */
  81630. Bone.prototype.getRotationMatrix = function (space, mesh) {
  81631. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81632. var result = BABYLON.Matrix.Identity();
  81633. this.getRotationMatrixToRef(space, mesh, result);
  81634. return result;
  81635. };
  81636. /**
  81637. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  81638. * @param space The space that the rotation should be in
  81639. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81640. * @param result The quaternion that the rotation should be copied to
  81641. */
  81642. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  81643. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81644. if (space == BABYLON.Space.LOCAL) {
  81645. this.getLocalMatrix().getRotationMatrixToRef(result);
  81646. }
  81647. else {
  81648. var mat = Bone._tmpMats[0];
  81649. var amat = this.getAbsoluteTransform();
  81650. if (mesh) {
  81651. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81652. }
  81653. else {
  81654. mat.copyFrom(amat);
  81655. }
  81656. mat.m[0] *= this._scalingDeterminant;
  81657. mat.m[1] *= this._scalingDeterminant;
  81658. mat.m[2] *= this._scalingDeterminant;
  81659. mat.getRotationMatrixToRef(result);
  81660. }
  81661. };
  81662. /**
  81663. * Get the world position of a point that is in the local space of the bone
  81664. * @param position The local position
  81665. * @param mesh The mesh that this bone is attached to
  81666. * @returns The world position
  81667. */
  81668. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  81669. if (mesh === void 0) { mesh = null; }
  81670. var result = BABYLON.Vector3.Zero();
  81671. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  81672. return result;
  81673. };
  81674. /**
  81675. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  81676. * @param position The local position
  81677. * @param mesh The mesh that this bone is attached to
  81678. * @param result The vector3 that the world position should be copied to
  81679. */
  81680. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  81681. if (mesh === void 0) { mesh = null; }
  81682. var wm = null;
  81683. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81684. if (mesh) {
  81685. wm = mesh.getWorldMatrix();
  81686. }
  81687. this._skeleton.computeAbsoluteTransforms();
  81688. var tmat = Bone._tmpMats[0];
  81689. if (mesh && wm) {
  81690. tmat.copyFrom(this.getAbsoluteTransform());
  81691. tmat.multiplyToRef(wm, tmat);
  81692. }
  81693. else {
  81694. tmat = this.getAbsoluteTransform();
  81695. }
  81696. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81697. };
  81698. /**
  81699. * Get the local position of a point that is in world space
  81700. * @param position The world position
  81701. * @param mesh The mesh that this bone is attached to
  81702. * @returns The local position
  81703. */
  81704. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  81705. if (mesh === void 0) { mesh = null; }
  81706. var result = BABYLON.Vector3.Zero();
  81707. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  81708. return result;
  81709. };
  81710. /**
  81711. * Get the local position of a point that is in world space and copy it to the result param
  81712. * @param position The world position
  81713. * @param mesh The mesh that this bone is attached to
  81714. * @param result The vector3 that the local position should be copied to
  81715. */
  81716. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  81717. if (mesh === void 0) { mesh = null; }
  81718. var wm = null;
  81719. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81720. if (mesh) {
  81721. wm = mesh.getWorldMatrix();
  81722. }
  81723. this._skeleton.computeAbsoluteTransforms();
  81724. var tmat = Bone._tmpMats[0];
  81725. tmat.copyFrom(this.getAbsoluteTransform());
  81726. if (mesh && wm) {
  81727. tmat.multiplyToRef(wm, tmat);
  81728. }
  81729. tmat.invert();
  81730. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81731. };
  81732. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81733. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  81734. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81735. return Bone;
  81736. }(BABYLON.Node));
  81737. BABYLON.Bone = Bone;
  81738. })(BABYLON || (BABYLON = {}));
  81739. //# sourceMappingURL=babylon.bone.js.map
  81740. var BABYLON;
  81741. (function (BABYLON) {
  81742. /**
  81743. * Class used to apply inverse kinematics to bones
  81744. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  81745. */
  81746. var BoneIKController = /** @class */ (function () {
  81747. /**
  81748. * Creates a new BoneIKController
  81749. * @param mesh defines the mesh to control
  81750. * @param bone defines the bone to control
  81751. * @param options defines options to set up the controller
  81752. */
  81753. function BoneIKController(mesh, bone, options) {
  81754. /**
  81755. * Gets or sets the target position
  81756. */
  81757. this.targetPosition = BABYLON.Vector3.Zero();
  81758. /**
  81759. * Gets or sets the pole target position
  81760. */
  81761. this.poleTargetPosition = BABYLON.Vector3.Zero();
  81762. /**
  81763. * Gets or sets the pole target local offset
  81764. */
  81765. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  81766. /**
  81767. * Gets or sets the pole angle
  81768. */
  81769. this.poleAngle = 0;
  81770. /**
  81771. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)
  81772. */
  81773. this.slerpAmount = 1;
  81774. this._bone1Quat = BABYLON.Quaternion.Identity();
  81775. this._bone1Mat = BABYLON.Matrix.Identity();
  81776. this._bone2Ang = Math.PI;
  81777. this._maxAngle = Math.PI;
  81778. this._rightHandedSystem = false;
  81779. this._bendAxis = BABYLON.Vector3.Right();
  81780. this._slerping = false;
  81781. this._adjustRoll = 0;
  81782. this._bone2 = bone;
  81783. this._bone1 = bone.getParent();
  81784. if (!this._bone1) {
  81785. return;
  81786. }
  81787. this.mesh = mesh;
  81788. var bonePos = bone.getPosition();
  81789. if (bone.getAbsoluteTransform().determinant() > 0) {
  81790. this._rightHandedSystem = true;
  81791. this._bendAxis.x = 0;
  81792. this._bendAxis.y = 0;
  81793. this._bendAxis.z = -1;
  81794. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  81795. this._adjustRoll = Math.PI * .5;
  81796. this._bendAxis.z = 1;
  81797. }
  81798. }
  81799. if (this._bone1.length) {
  81800. var boneScale1 = this._bone1.getScale();
  81801. var boneScale2 = this._bone2.getScale();
  81802. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  81803. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  81804. }
  81805. else if (this._bone1.children[0]) {
  81806. mesh.computeWorldMatrix(true);
  81807. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  81808. var pos2 = this._bone2.getAbsolutePosition(mesh);
  81809. var pos3 = this._bone1.getAbsolutePosition(mesh);
  81810. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  81811. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  81812. }
  81813. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  81814. this.maxAngle = Math.PI;
  81815. if (options) {
  81816. if (options.targetMesh) {
  81817. this.targetMesh = options.targetMesh;
  81818. this.targetMesh.computeWorldMatrix(true);
  81819. }
  81820. if (options.poleTargetMesh) {
  81821. this.poleTargetMesh = options.poleTargetMesh;
  81822. this.poleTargetMesh.computeWorldMatrix(true);
  81823. }
  81824. else if (options.poleTargetBone) {
  81825. this.poleTargetBone = options.poleTargetBone;
  81826. }
  81827. else if (this._bone1.getParent()) {
  81828. this.poleTargetBone = this._bone1.getParent();
  81829. }
  81830. if (options.poleTargetLocalOffset) {
  81831. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  81832. }
  81833. if (options.poleAngle) {
  81834. this.poleAngle = options.poleAngle;
  81835. }
  81836. if (options.bendAxis) {
  81837. this._bendAxis.copyFrom(options.bendAxis);
  81838. }
  81839. if (options.maxAngle) {
  81840. this.maxAngle = options.maxAngle;
  81841. }
  81842. if (options.slerpAmount) {
  81843. this.slerpAmount = options.slerpAmount;
  81844. }
  81845. }
  81846. }
  81847. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  81848. /**
  81849. * Gets or sets maximum allowed angle
  81850. */
  81851. get: function () {
  81852. return this._maxAngle;
  81853. },
  81854. set: function (value) {
  81855. this._setMaxAngle(value);
  81856. },
  81857. enumerable: true,
  81858. configurable: true
  81859. });
  81860. BoneIKController.prototype._setMaxAngle = function (ang) {
  81861. if (ang < 0) {
  81862. ang = 0;
  81863. }
  81864. if (ang > Math.PI || ang == undefined) {
  81865. ang = Math.PI;
  81866. }
  81867. this._maxAngle = ang;
  81868. var a = this._bone1Length;
  81869. var b = this._bone2Length;
  81870. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  81871. };
  81872. /**
  81873. * Force the controller to update the bones
  81874. */
  81875. BoneIKController.prototype.update = function () {
  81876. var bone1 = this._bone1;
  81877. if (!bone1) {
  81878. return;
  81879. }
  81880. var target = this.targetPosition;
  81881. var poleTarget = this.poleTargetPosition;
  81882. var mat1 = BoneIKController._tmpMats[0];
  81883. var mat2 = BoneIKController._tmpMats[1];
  81884. if (this.targetMesh) {
  81885. target.copyFrom(this.targetMesh.getAbsolutePosition());
  81886. }
  81887. if (this.poleTargetBone) {
  81888. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  81889. }
  81890. else if (this.poleTargetMesh) {
  81891. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  81892. }
  81893. var bonePos = BoneIKController._tmpVecs[0];
  81894. var zaxis = BoneIKController._tmpVecs[1];
  81895. var xaxis = BoneIKController._tmpVecs[2];
  81896. var yaxis = BoneIKController._tmpVecs[3];
  81897. var upAxis = BoneIKController._tmpVecs[4];
  81898. var _tmpQuat = BoneIKController._tmpQuat;
  81899. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  81900. poleTarget.subtractToRef(bonePos, upAxis);
  81901. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  81902. upAxis.y = 1;
  81903. }
  81904. else {
  81905. upAxis.normalize();
  81906. }
  81907. target.subtractToRef(bonePos, yaxis);
  81908. yaxis.normalize();
  81909. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  81910. zaxis.normalize();
  81911. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  81912. xaxis.normalize();
  81913. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  81914. var a = this._bone1Length;
  81915. var b = this._bone2Length;
  81916. var c = BABYLON.Vector3.Distance(bonePos, target);
  81917. if (this._maxReach > 0) {
  81918. c = Math.min(this._maxReach, c);
  81919. }
  81920. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  81921. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  81922. if (acosa > 1) {
  81923. acosa = 1;
  81924. }
  81925. if (acosb > 1) {
  81926. acosb = 1;
  81927. }
  81928. if (acosa < -1) {
  81929. acosa = -1;
  81930. }
  81931. if (acosb < -1) {
  81932. acosb = -1;
  81933. }
  81934. var angA = Math.acos(acosa);
  81935. var angB = Math.acos(acosb);
  81936. var angC = -angA - angB;
  81937. if (this._rightHandedSystem) {
  81938. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  81939. mat2.multiplyToRef(mat1, mat1);
  81940. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  81941. mat2.multiplyToRef(mat1, mat1);
  81942. }
  81943. else {
  81944. var _tmpVec = BoneIKController._tmpVecs[5];
  81945. _tmpVec.copyFrom(this._bendAxis);
  81946. _tmpVec.x *= -1;
  81947. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  81948. mat2.multiplyToRef(mat1, mat1);
  81949. }
  81950. if (this.poleAngle) {
  81951. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  81952. mat1.multiplyToRef(mat2, mat1);
  81953. }
  81954. if (this._bone1) {
  81955. if (this.slerpAmount < 1) {
  81956. if (!this._slerping) {
  81957. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  81958. }
  81959. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  81960. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  81961. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  81962. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  81963. this._slerping = true;
  81964. }
  81965. else {
  81966. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  81967. this._bone1Mat.copyFrom(mat1);
  81968. this._slerping = false;
  81969. }
  81970. }
  81971. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  81972. this._bone2Ang = angC;
  81973. };
  81974. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81975. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  81976. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81977. return BoneIKController;
  81978. }());
  81979. BABYLON.BoneIKController = BoneIKController;
  81980. })(BABYLON || (BABYLON = {}));
  81981. //# sourceMappingURL=babylon.boneIKController.js.map
  81982. var BABYLON;
  81983. (function (BABYLON) {
  81984. /**
  81985. * Class used to make a bone look toward a point in space
  81986. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  81987. */
  81988. var BoneLookController = /** @class */ (function () {
  81989. /**
  81990. * Create a BoneLookController
  81991. * @param mesh the mesh that the bone belongs to
  81992. * @param bone the bone that will be looking to the target
  81993. * @param target the target Vector3 to look at
  81994. * @param settings optional settings:
  81995. * * maxYaw: the maximum angle the bone will yaw to
  81996. * * minYaw: the minimum angle the bone will yaw to
  81997. * * maxPitch: the maximum angle the bone will pitch to
  81998. * * minPitch: the minimum angle the bone will yaw to
  81999. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  82000. * * upAxis: the up axis of the coordinate system
  82001. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  82002. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  82003. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  82004. * * adjustYaw: used to make an adjustment to the yaw of the bone
  82005. * * adjustPitch: used to make an adjustment to the pitch of the bone
  82006. * * adjustRoll: used to make an adjustment to the roll of the bone
  82007. **/
  82008. function BoneLookController(mesh, bone, target, options) {
  82009. /**
  82010. * The up axis of the coordinate system that is used when the bone is rotated
  82011. */
  82012. this.upAxis = BABYLON.Vector3.Up();
  82013. /**
  82014. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  82015. */
  82016. this.upAxisSpace = BABYLON.Space.LOCAL;
  82017. /**
  82018. * Used to make an adjustment to the yaw of the bone
  82019. */
  82020. this.adjustYaw = 0;
  82021. /**
  82022. * Used to make an adjustment to the pitch of the bone
  82023. */
  82024. this.adjustPitch = 0;
  82025. /**
  82026. * Used to make an adjustment to the roll of the bone
  82027. */
  82028. this.adjustRoll = 0;
  82029. /**
  82030. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)
  82031. */
  82032. this.slerpAmount = 1;
  82033. this._boneQuat = BABYLON.Quaternion.Identity();
  82034. this._slerping = false;
  82035. this._firstFrameSkipped = false;
  82036. this._fowardAxis = BABYLON.Vector3.Forward();
  82037. this.mesh = mesh;
  82038. this.bone = bone;
  82039. this.target = target;
  82040. if (options) {
  82041. if (options.adjustYaw) {
  82042. this.adjustYaw = options.adjustYaw;
  82043. }
  82044. if (options.adjustPitch) {
  82045. this.adjustPitch = options.adjustPitch;
  82046. }
  82047. if (options.adjustRoll) {
  82048. this.adjustRoll = options.adjustRoll;
  82049. }
  82050. if (options.maxYaw != null) {
  82051. this.maxYaw = options.maxYaw;
  82052. }
  82053. else {
  82054. this.maxYaw = Math.PI;
  82055. }
  82056. if (options.minYaw != null) {
  82057. this.minYaw = options.minYaw;
  82058. }
  82059. else {
  82060. this.minYaw = -Math.PI;
  82061. }
  82062. if (options.maxPitch != null) {
  82063. this.maxPitch = options.maxPitch;
  82064. }
  82065. else {
  82066. this.maxPitch = Math.PI;
  82067. }
  82068. if (options.minPitch != null) {
  82069. this.minPitch = options.minPitch;
  82070. }
  82071. else {
  82072. this.minPitch = -Math.PI;
  82073. }
  82074. if (options.slerpAmount != null) {
  82075. this.slerpAmount = options.slerpAmount;
  82076. }
  82077. if (options.upAxis != null) {
  82078. this.upAxis = options.upAxis;
  82079. }
  82080. if (options.upAxisSpace != null) {
  82081. this.upAxisSpace = options.upAxisSpace;
  82082. }
  82083. if (options.yawAxis != null || options.pitchAxis != null) {
  82084. var newYawAxis = BABYLON.Axis.Y;
  82085. var newPitchAxis = BABYLON.Axis.X;
  82086. if (options.yawAxis != null) {
  82087. newYawAxis = options.yawAxis.clone();
  82088. newYawAxis.normalize();
  82089. }
  82090. if (options.pitchAxis != null) {
  82091. newPitchAxis = options.pitchAxis.clone();
  82092. newPitchAxis.normalize();
  82093. }
  82094. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  82095. this._transformYawPitch = BABYLON.Matrix.Identity();
  82096. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  82097. this._transformYawPitchInv = this._transformYawPitch.clone();
  82098. this._transformYawPitch.invert();
  82099. }
  82100. }
  82101. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  82102. this.upAxisSpace = BABYLON.Space.LOCAL;
  82103. }
  82104. }
  82105. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  82106. /**
  82107. * Gets or sets the minimum yaw angle that the bone can look to
  82108. */
  82109. get: function () {
  82110. return this._minYaw;
  82111. },
  82112. set: function (value) {
  82113. this._minYaw = value;
  82114. this._minYawSin = Math.sin(value);
  82115. this._minYawCos = Math.cos(value);
  82116. if (this._maxYaw != null) {
  82117. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82118. this._yawRange = this._maxYaw - this._minYaw;
  82119. }
  82120. },
  82121. enumerable: true,
  82122. configurable: true
  82123. });
  82124. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  82125. /**
  82126. * Gets or sets the maximum yaw angle that the bone can look to
  82127. */
  82128. get: function () {
  82129. return this._maxYaw;
  82130. },
  82131. set: function (value) {
  82132. this._maxYaw = value;
  82133. this._maxYawSin = Math.sin(value);
  82134. this._maxYawCos = Math.cos(value);
  82135. if (this._minYaw != null) {
  82136. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82137. this._yawRange = this._maxYaw - this._minYaw;
  82138. }
  82139. },
  82140. enumerable: true,
  82141. configurable: true
  82142. });
  82143. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  82144. /**
  82145. * Gets or sets the minimum pitch angle that the bone can look to
  82146. */
  82147. get: function () {
  82148. return this._minPitch;
  82149. },
  82150. set: function (value) {
  82151. this._minPitch = value;
  82152. this._minPitchTan = Math.tan(value);
  82153. },
  82154. enumerable: true,
  82155. configurable: true
  82156. });
  82157. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  82158. /**
  82159. * Gets or sets the maximum pitch angle that the bone can look to
  82160. */
  82161. get: function () {
  82162. return this._maxPitch;
  82163. },
  82164. set: function (value) {
  82165. this._maxPitch = value;
  82166. this._maxPitchTan = Math.tan(value);
  82167. },
  82168. enumerable: true,
  82169. configurable: true
  82170. });
  82171. /**
  82172. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  82173. */
  82174. BoneLookController.prototype.update = function () {
  82175. //skip the first frame when slerping so that the mesh rotation is correct
  82176. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  82177. this._firstFrameSkipped = true;
  82178. return;
  82179. }
  82180. var bone = this.bone;
  82181. var bonePos = BoneLookController._tmpVecs[0];
  82182. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  82183. var target = this.target;
  82184. var _tmpMat1 = BoneLookController._tmpMats[0];
  82185. var _tmpMat2 = BoneLookController._tmpMats[1];
  82186. var mesh = this.mesh;
  82187. var parentBone = bone.getParent();
  82188. var upAxis = BoneLookController._tmpVecs[1];
  82189. upAxis.copyFrom(this.upAxis);
  82190. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  82191. if (this._transformYawPitch) {
  82192. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  82193. }
  82194. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  82195. }
  82196. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  82197. mesh.getDirectionToRef(upAxis, upAxis);
  82198. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  82199. upAxis.normalize();
  82200. }
  82201. }
  82202. var checkYaw = false;
  82203. var checkPitch = false;
  82204. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  82205. checkYaw = true;
  82206. }
  82207. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  82208. checkPitch = true;
  82209. }
  82210. if (checkYaw || checkPitch) {
  82211. var spaceMat = BoneLookController._tmpMats[2];
  82212. var spaceMatInv = BoneLookController._tmpMats[3];
  82213. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  82214. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  82215. }
  82216. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  82217. spaceMat.copyFrom(mesh.getWorldMatrix());
  82218. }
  82219. else {
  82220. var forwardAxis = BoneLookController._tmpVecs[2];
  82221. forwardAxis.copyFrom(this._fowardAxis);
  82222. if (this._transformYawPitch) {
  82223. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  82224. }
  82225. if (parentBone) {
  82226. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  82227. }
  82228. else {
  82229. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  82230. }
  82231. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  82232. rightAxis.normalize();
  82233. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  82234. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  82235. }
  82236. spaceMat.invertToRef(spaceMatInv);
  82237. var xzlen = null;
  82238. if (checkPitch) {
  82239. var localTarget = BoneLookController._tmpVecs[3];
  82240. target.subtractToRef(bonePos, localTarget);
  82241. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82242. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82243. var pitch = Math.atan2(localTarget.y, xzlen);
  82244. var newPitch = pitch;
  82245. if (pitch > this._maxPitch) {
  82246. localTarget.y = this._maxPitchTan * xzlen;
  82247. newPitch = this._maxPitch;
  82248. }
  82249. else if (pitch < this._minPitch) {
  82250. localTarget.y = this._minPitchTan * xzlen;
  82251. newPitch = this._minPitch;
  82252. }
  82253. if (pitch != newPitch) {
  82254. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82255. localTarget.addInPlace(bonePos);
  82256. target = localTarget;
  82257. }
  82258. }
  82259. if (checkYaw) {
  82260. var localTarget = BoneLookController._tmpVecs[4];
  82261. target.subtractToRef(bonePos, localTarget);
  82262. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82263. var yaw = Math.atan2(localTarget.x, localTarget.z);
  82264. var newYaw = yaw;
  82265. if (yaw > this._maxYaw || yaw < this._minYaw) {
  82266. if (xzlen == null) {
  82267. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82268. }
  82269. if (this._yawRange > Math.PI) {
  82270. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  82271. localTarget.z = this._maxYawCos * xzlen;
  82272. localTarget.x = this._maxYawSin * xzlen;
  82273. newYaw = this._maxYaw;
  82274. }
  82275. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  82276. localTarget.z = this._minYawCos * xzlen;
  82277. localTarget.x = this._minYawSin * xzlen;
  82278. newYaw = this._minYaw;
  82279. }
  82280. }
  82281. else {
  82282. if (yaw > this._maxYaw) {
  82283. localTarget.z = this._maxYawCos * xzlen;
  82284. localTarget.x = this._maxYawSin * xzlen;
  82285. newYaw = this._maxYaw;
  82286. }
  82287. else if (yaw < this._minYaw) {
  82288. localTarget.z = this._minYawCos * xzlen;
  82289. localTarget.x = this._minYawSin * xzlen;
  82290. newYaw = this._minYaw;
  82291. }
  82292. }
  82293. }
  82294. if (this._slerping && this._yawRange > Math.PI) {
  82295. //are we going to be crossing into the min/max region?
  82296. var boneFwd = BoneLookController._tmpVecs[8];
  82297. boneFwd.copyFrom(BABYLON.Axis.Z);
  82298. if (this._transformYawPitch) {
  82299. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  82300. }
  82301. var boneRotMat = BoneLookController._tmpMats[4];
  82302. this._boneQuat.toRotationMatrix(boneRotMat);
  82303. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  82304. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  82305. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  82306. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  82307. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  82308. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  82309. if (angBtwTar > angBtwMidYaw) {
  82310. if (xzlen == null) {
  82311. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82312. }
  82313. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  82314. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  82315. if (angBtwMin < angBtwMax) {
  82316. newYaw = boneYaw + Math.PI * .75;
  82317. localTarget.z = Math.cos(newYaw) * xzlen;
  82318. localTarget.x = Math.sin(newYaw) * xzlen;
  82319. }
  82320. else {
  82321. newYaw = boneYaw - Math.PI * .75;
  82322. localTarget.z = Math.cos(newYaw) * xzlen;
  82323. localTarget.x = Math.sin(newYaw) * xzlen;
  82324. }
  82325. }
  82326. }
  82327. if (yaw != newYaw) {
  82328. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82329. localTarget.addInPlace(bonePos);
  82330. target = localTarget;
  82331. }
  82332. }
  82333. }
  82334. var zaxis = BoneLookController._tmpVecs[5];
  82335. var xaxis = BoneLookController._tmpVecs[6];
  82336. var yaxis = BoneLookController._tmpVecs[7];
  82337. var _tmpQuat = BoneLookController._tmpQuat;
  82338. target.subtractToRef(bonePos, zaxis);
  82339. zaxis.normalize();
  82340. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  82341. xaxis.normalize();
  82342. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  82343. yaxis.normalize();
  82344. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  82345. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  82346. return;
  82347. }
  82348. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  82349. return;
  82350. }
  82351. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  82352. return;
  82353. }
  82354. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  82355. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  82356. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  82357. }
  82358. if (this.slerpAmount < 1) {
  82359. if (!this._slerping) {
  82360. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  82361. }
  82362. if (this._transformYawPitch) {
  82363. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82364. }
  82365. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  82366. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  82367. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  82368. this._slerping = true;
  82369. }
  82370. else {
  82371. if (this._transformYawPitch) {
  82372. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82373. }
  82374. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  82375. this._slerping = false;
  82376. }
  82377. };
  82378. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  82379. var angDiff = ang2 - ang1;
  82380. angDiff %= Math.PI * 2;
  82381. if (angDiff > Math.PI) {
  82382. angDiff -= Math.PI * 2;
  82383. }
  82384. else if (angDiff < -Math.PI) {
  82385. angDiff += Math.PI * 2;
  82386. }
  82387. return angDiff;
  82388. };
  82389. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  82390. ang1 %= (2 * Math.PI);
  82391. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82392. ang2 %= (2 * Math.PI);
  82393. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82394. var ab = 0;
  82395. if (ang1 < ang2) {
  82396. ab = ang2 - ang1;
  82397. }
  82398. else {
  82399. ab = ang1 - ang2;
  82400. }
  82401. if (ab > Math.PI) {
  82402. ab = Math.PI * 2 - ab;
  82403. }
  82404. return ab;
  82405. };
  82406. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  82407. ang %= (2 * Math.PI);
  82408. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  82409. ang1 %= (2 * Math.PI);
  82410. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82411. ang2 %= (2 * Math.PI);
  82412. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82413. if (ang1 < ang2) {
  82414. if (ang > ang1 && ang < ang2) {
  82415. return true;
  82416. }
  82417. }
  82418. else {
  82419. if (ang > ang2 && ang < ang1) {
  82420. return true;
  82421. }
  82422. }
  82423. return false;
  82424. };
  82425. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82426. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  82427. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82428. return BoneLookController;
  82429. }());
  82430. BABYLON.BoneLookController = BoneLookController;
  82431. })(BABYLON || (BABYLON = {}));
  82432. //# sourceMappingURL=babylon.boneLookController.js.map
  82433. var BABYLON;
  82434. (function (BABYLON) {
  82435. /**
  82436. * Class used to handle skinning animations
  82437. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82438. */
  82439. var Skeleton = /** @class */ (function () {
  82440. /**
  82441. * Creates a new skeleton
  82442. * @param name defines the skeleton name
  82443. * @param id defines the skeleton Id
  82444. * @param scene defines the hosting scene
  82445. */
  82446. function Skeleton(
  82447. /** defines the skeleton name */
  82448. name,
  82449. /** defines the skeleton Id */
  82450. id, scene) {
  82451. this.name = name;
  82452. this.id = id;
  82453. /**
  82454. * Gets the list of child bones
  82455. */
  82456. this.bones = new Array();
  82457. /**
  82458. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  82459. */
  82460. this.needInitialSkinMatrix = false;
  82461. this._isDirty = true;
  82462. this._meshesWithPoseMatrix = new Array();
  82463. this._identity = BABYLON.Matrix.Identity();
  82464. this._ranges = {};
  82465. this._lastAbsoluteTransformsUpdateId = -1;
  82466. /**
  82467. * Specifies if the skeleton should be serialized
  82468. */
  82469. this.doNotSerialize = false;
  82470. this._animationPropertiesOverride = null;
  82471. // Events
  82472. /**
  82473. * An observable triggered before computing the skeleton's matrices
  82474. */
  82475. this.onBeforeComputeObservable = new BABYLON.Observable();
  82476. this.bones = [];
  82477. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82478. scene.skeletons.push(this);
  82479. //make sure it will recalculate the matrix next time prepare is called.
  82480. this._isDirty = true;
  82481. }
  82482. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  82483. /**
  82484. * Gets or sets the animation properties override
  82485. */
  82486. get: function () {
  82487. if (!this._animationPropertiesOverride) {
  82488. return this._scene.animationPropertiesOverride;
  82489. }
  82490. return this._animationPropertiesOverride;
  82491. },
  82492. set: function (value) {
  82493. this._animationPropertiesOverride = value;
  82494. },
  82495. enumerable: true,
  82496. configurable: true
  82497. });
  82498. // Members
  82499. /**
  82500. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  82501. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  82502. * @returns a Float32Array containing matrices data
  82503. */
  82504. Skeleton.prototype.getTransformMatrices = function (mesh) {
  82505. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  82506. return mesh._bonesTransformMatrices;
  82507. }
  82508. if (!this._transformMatrices) {
  82509. this.prepare();
  82510. }
  82511. return this._transformMatrices;
  82512. };
  82513. /**
  82514. * Gets the current hosting scene
  82515. * @returns a scene object
  82516. */
  82517. Skeleton.prototype.getScene = function () {
  82518. return this._scene;
  82519. };
  82520. // Methods
  82521. /**
  82522. * Gets a string representing the current skeleton data
  82523. * @param fullDetails defines a boolean indicating if we want a verbose version
  82524. * @returns a string representing the current skeleton data
  82525. */
  82526. Skeleton.prototype.toString = function (fullDetails) {
  82527. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  82528. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  82529. if (fullDetails) {
  82530. ret += ", Ranges: {";
  82531. var first = true;
  82532. for (var name_1 in this._ranges) {
  82533. if (first) {
  82534. ret += ", ";
  82535. first = false;
  82536. }
  82537. ret += name_1;
  82538. }
  82539. ret += "}";
  82540. }
  82541. return ret;
  82542. };
  82543. /**
  82544. * Get bone's index searching by name
  82545. * @param name defines bone's name to search for
  82546. * @return the indice of the bone. Returns -1 if not found
  82547. */
  82548. Skeleton.prototype.getBoneIndexByName = function (name) {
  82549. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  82550. if (this.bones[boneIndex].name === name) {
  82551. return boneIndex;
  82552. }
  82553. }
  82554. return -1;
  82555. };
  82556. /**
  82557. * Creater a new animation range
  82558. * @param name defines the name of the range
  82559. * @param from defines the start key
  82560. * @param to defines the end key
  82561. */
  82562. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  82563. // check name not already in use
  82564. if (!this._ranges[name]) {
  82565. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  82566. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82567. if (this.bones[i].animations[0]) {
  82568. this.bones[i].animations[0].createRange(name, from, to);
  82569. }
  82570. }
  82571. }
  82572. };
  82573. /**
  82574. * Delete a specific animation range
  82575. * @param name defines the name of the range
  82576. * @param deleteFrames defines if frames must be removed as well
  82577. */
  82578. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  82579. if (deleteFrames === void 0) { deleteFrames = true; }
  82580. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82581. if (this.bones[i].animations[0]) {
  82582. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  82583. }
  82584. }
  82585. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  82586. };
  82587. /**
  82588. * Gets a specific animation range
  82589. * @param name defines the name of the range to look for
  82590. * @returns the requested animation range or null if not found
  82591. */
  82592. Skeleton.prototype.getAnimationRange = function (name) {
  82593. return this._ranges[name];
  82594. };
  82595. /**
  82596. * Gets the list of all animation ranges defined on this skeleton
  82597. * @returns an array
  82598. */
  82599. Skeleton.prototype.getAnimationRanges = function () {
  82600. var animationRanges = [];
  82601. var name;
  82602. var i = 0;
  82603. for (name in this._ranges) {
  82604. animationRanges[i] = this._ranges[name];
  82605. i++;
  82606. }
  82607. return animationRanges;
  82608. };
  82609. /**
  82610. * Copy animation range from a source skeleton.
  82611. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  82612. * @param source defines the source skeleton
  82613. * @param name defines the name of the range to copy
  82614. * @param rescaleAsRequired defines if rescaling must be applied if required
  82615. * @returns true if operation was successful
  82616. */
  82617. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  82618. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82619. if (this._ranges[name] || !source.getAnimationRange(name)) {
  82620. return false;
  82621. }
  82622. var ret = true;
  82623. var frameOffset = this._getHighestAnimationFrame() + 1;
  82624. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  82625. var boneDict = {};
  82626. var sourceBones = source.bones;
  82627. var nBones;
  82628. var i;
  82629. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  82630. boneDict[sourceBones[i].name] = sourceBones[i];
  82631. }
  82632. if (this.bones.length !== sourceBones.length) {
  82633. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  82634. ret = false;
  82635. }
  82636. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  82637. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  82638. var boneName = this.bones[i].name;
  82639. var sourceBone = boneDict[boneName];
  82640. if (sourceBone) {
  82641. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  82642. }
  82643. else {
  82644. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  82645. ret = false;
  82646. }
  82647. }
  82648. // do not call createAnimationRange(), since it also is done to bones, which was already done
  82649. var range = source.getAnimationRange(name);
  82650. if (range) {
  82651. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  82652. }
  82653. return ret;
  82654. };
  82655. /**
  82656. * Forces the skeleton to go to rest pose
  82657. */
  82658. Skeleton.prototype.returnToRest = function () {
  82659. for (var index = 0; index < this.bones.length; index++) {
  82660. this.bones[index].returnToRest();
  82661. }
  82662. };
  82663. Skeleton.prototype._getHighestAnimationFrame = function () {
  82664. var ret = 0;
  82665. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82666. if (this.bones[i].animations[0]) {
  82667. var highest = this.bones[i].animations[0].getHighestFrame();
  82668. if (ret < highest) {
  82669. ret = highest;
  82670. }
  82671. }
  82672. }
  82673. return ret;
  82674. };
  82675. /**
  82676. * Begin a specific animation range
  82677. * @param name defines the name of the range to start
  82678. * @param loop defines if looping must be turned on (false by default)
  82679. * @param speedRatio defines the speed ratio to apply (1 by default)
  82680. * @param onAnimationEnd defines a callback which will be called when animation will end
  82681. * @returns a new animatable
  82682. */
  82683. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  82684. var range = this.getAnimationRange(name);
  82685. if (!range) {
  82686. return null;
  82687. }
  82688. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  82689. };
  82690. /** @hidden */
  82691. Skeleton.prototype._markAsDirty = function () {
  82692. this._isDirty = true;
  82693. };
  82694. /** @hidden */
  82695. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  82696. this._meshesWithPoseMatrix.push(mesh);
  82697. };
  82698. /** @hidden */
  82699. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  82700. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  82701. if (index > -1) {
  82702. this._meshesWithPoseMatrix.splice(index, 1);
  82703. }
  82704. };
  82705. /** @hidden */
  82706. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  82707. this.onBeforeComputeObservable.notifyObservers(this);
  82708. for (var index = 0; index < this.bones.length; index++) {
  82709. var bone = this.bones[index];
  82710. var parentBone = bone.getParent();
  82711. if (parentBone) {
  82712. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  82713. }
  82714. else {
  82715. if (initialSkinMatrix) {
  82716. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  82717. }
  82718. else {
  82719. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  82720. }
  82721. }
  82722. if (bone._index !== -1) {
  82723. var mappedIndex = bone._index === null ? index : bone._index;
  82724. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  82725. }
  82726. }
  82727. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  82728. };
  82729. /**
  82730. * Build all resources required to render a skeleton
  82731. */
  82732. Skeleton.prototype.prepare = function () {
  82733. if (!this._isDirty) {
  82734. return;
  82735. }
  82736. if (this.needInitialSkinMatrix) {
  82737. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  82738. var mesh = this._meshesWithPoseMatrix[index];
  82739. var poseMatrix = mesh.getPoseMatrix();
  82740. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  82741. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82742. }
  82743. if (this._synchronizedWithMesh !== mesh) {
  82744. this._synchronizedWithMesh = mesh;
  82745. // Prepare bones
  82746. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  82747. var bone = this.bones[boneIndex];
  82748. if (!bone.getParent()) {
  82749. var matrix = bone.getBaseMatrix();
  82750. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  82751. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  82752. }
  82753. }
  82754. }
  82755. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  82756. }
  82757. }
  82758. else {
  82759. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  82760. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82761. }
  82762. this._computeTransformMatrices(this._transformMatrices, null);
  82763. }
  82764. this._isDirty = false;
  82765. this._scene._activeBones.addCount(this.bones.length, false);
  82766. };
  82767. /**
  82768. * Gets the list of animatables currently running for this skeleton
  82769. * @returns an array of animatables
  82770. */
  82771. Skeleton.prototype.getAnimatables = function () {
  82772. if (!this._animatables || this._animatables.length !== this.bones.length) {
  82773. this._animatables = [];
  82774. for (var index = 0; index < this.bones.length; index++) {
  82775. this._animatables.push(this.bones[index]);
  82776. }
  82777. }
  82778. return this._animatables;
  82779. };
  82780. /**
  82781. * Clone the current skeleton
  82782. * @param name defines the name of the new skeleton
  82783. * @param id defines the id of the enw skeleton
  82784. * @returns the new skeleton
  82785. */
  82786. Skeleton.prototype.clone = function (name, id) {
  82787. var result = new Skeleton(name, id || name, this._scene);
  82788. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82789. for (var index = 0; index < this.bones.length; index++) {
  82790. var source = this.bones[index];
  82791. var parentBone = null;
  82792. var parent_1 = source.getParent();
  82793. if (parent_1) {
  82794. var parentIndex = this.bones.indexOf(parent_1);
  82795. parentBone = result.bones[parentIndex];
  82796. }
  82797. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  82798. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  82799. }
  82800. if (this._ranges) {
  82801. result._ranges = {};
  82802. for (var rangeName in this._ranges) {
  82803. var range = this._ranges[rangeName];
  82804. if (range) {
  82805. result._ranges[rangeName] = range.clone();
  82806. }
  82807. }
  82808. }
  82809. this._isDirty = true;
  82810. return result;
  82811. };
  82812. /**
  82813. * Enable animation blending for this skeleton
  82814. * @param blendingSpeed defines the blending speed to apply
  82815. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  82816. */
  82817. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  82818. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  82819. this.bones.forEach(function (bone) {
  82820. bone.animations.forEach(function (animation) {
  82821. animation.enableBlending = true;
  82822. animation.blendingSpeed = blendingSpeed;
  82823. });
  82824. });
  82825. };
  82826. /**
  82827. * Releases all resources associated with the current skeleton
  82828. */
  82829. Skeleton.prototype.dispose = function () {
  82830. this._meshesWithPoseMatrix = [];
  82831. // Animations
  82832. this.getScene().stopAnimation(this);
  82833. // Remove from scene
  82834. this.getScene().removeSkeleton(this);
  82835. };
  82836. /**
  82837. * Serialize the skeleton in a JSON object
  82838. * @returns a JSON object
  82839. */
  82840. Skeleton.prototype.serialize = function () {
  82841. var serializationObject = {};
  82842. serializationObject.name = this.name;
  82843. serializationObject.id = this.id;
  82844. if (this.dimensionsAtRest) {
  82845. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  82846. }
  82847. serializationObject.bones = [];
  82848. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82849. for (var index = 0; index < this.bones.length; index++) {
  82850. var bone = this.bones[index];
  82851. var parent_2 = bone.getParent();
  82852. var serializedBone = {
  82853. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  82854. name: bone.name,
  82855. matrix: bone.getBaseMatrix().toArray(),
  82856. rest: bone.getRestPose().toArray()
  82857. };
  82858. serializationObject.bones.push(serializedBone);
  82859. if (bone.length) {
  82860. serializedBone.length = bone.length;
  82861. }
  82862. if (bone.metadata) {
  82863. serializedBone.metadata = bone.metadata;
  82864. }
  82865. if (bone.animations && bone.animations.length > 0) {
  82866. serializedBone.animation = bone.animations[0].serialize();
  82867. }
  82868. serializationObject.ranges = [];
  82869. for (var name in this._ranges) {
  82870. var source = this._ranges[name];
  82871. if (!source) {
  82872. continue;
  82873. }
  82874. var range = {};
  82875. range.name = name;
  82876. range.from = source.from;
  82877. range.to = source.to;
  82878. serializationObject.ranges.push(range);
  82879. }
  82880. }
  82881. return serializationObject;
  82882. };
  82883. /**
  82884. * Creates a new skeleton from serialized data
  82885. * @param parsedSkeleton defines the serialized data
  82886. * @param scene defines the hosting scene
  82887. * @returns a new skeleton
  82888. */
  82889. Skeleton.Parse = function (parsedSkeleton, scene) {
  82890. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  82891. if (parsedSkeleton.dimensionsAtRest) {
  82892. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  82893. }
  82894. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  82895. var index;
  82896. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  82897. var parsedBone = parsedSkeleton.bones[index];
  82898. var parentBone = null;
  82899. if (parsedBone.parentBoneIndex > -1) {
  82900. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  82901. }
  82902. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  82903. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  82904. if (parsedBone.length) {
  82905. bone.length = parsedBone.length;
  82906. }
  82907. if (parsedBone.metadata) {
  82908. bone.metadata = parsedBone.metadata;
  82909. }
  82910. if (parsedBone.animation) {
  82911. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  82912. }
  82913. }
  82914. // placed after bones, so createAnimationRange can cascade down
  82915. if (parsedSkeleton.ranges) {
  82916. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  82917. var data = parsedSkeleton.ranges[index];
  82918. skeleton.createAnimationRange(data.name, data.from, data.to);
  82919. }
  82920. }
  82921. return skeleton;
  82922. };
  82923. /**
  82924. * Compute all node absolute transforms
  82925. * @param forceUpdate defines if computation must be done even if cache is up to date
  82926. */
  82927. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  82928. if (forceUpdate === void 0) { forceUpdate = false; }
  82929. var renderId = this._scene.getRenderId();
  82930. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  82931. this.bones[0].computeAbsoluteTransforms();
  82932. this._lastAbsoluteTransformsUpdateId = renderId;
  82933. }
  82934. };
  82935. /**
  82936. * Gets the root pose matrix
  82937. * @returns a matrix
  82938. */
  82939. Skeleton.prototype.getPoseMatrix = function () {
  82940. var poseMatrix = null;
  82941. if (this._meshesWithPoseMatrix.length > 0) {
  82942. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  82943. }
  82944. return poseMatrix;
  82945. };
  82946. /**
  82947. * Sorts bones per internal index
  82948. */
  82949. Skeleton.prototype.sortBones = function () {
  82950. var bones = new Array();
  82951. var visited = new Array(this.bones.length);
  82952. for (var index = 0; index < this.bones.length; index++) {
  82953. this._sortBones(index, bones, visited);
  82954. }
  82955. this.bones = bones;
  82956. };
  82957. Skeleton.prototype._sortBones = function (index, bones, visited) {
  82958. if (visited[index]) {
  82959. return;
  82960. }
  82961. visited[index] = true;
  82962. var bone = this.bones[index];
  82963. if (bone._index === undefined) {
  82964. bone._index = index;
  82965. }
  82966. var parentBone = bone.getParent();
  82967. if (parentBone) {
  82968. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  82969. }
  82970. bones.push(bone);
  82971. };
  82972. return Skeleton;
  82973. }());
  82974. BABYLON.Skeleton = Skeleton;
  82975. })(BABYLON || (BABYLON = {}));
  82976. //# sourceMappingURL=babylon.skeleton.js.map
  82977. var BABYLON;
  82978. (function (BABYLON) {
  82979. ;
  82980. /**
  82981. * This groups tools to convert HDR texture to native colors array.
  82982. */
  82983. var HDRTools = /** @class */ (function () {
  82984. function HDRTools() {
  82985. }
  82986. HDRTools.Ldexp = function (mantissa, exponent) {
  82987. if (exponent > 1023) {
  82988. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82989. }
  82990. if (exponent < -1074) {
  82991. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82992. }
  82993. return mantissa * Math.pow(2, exponent);
  82994. };
  82995. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82996. if (exponent > 0) { /*nonzero pixel*/
  82997. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82998. float32array[index + 0] = red * exponent;
  82999. float32array[index + 1] = green * exponent;
  83000. float32array[index + 2] = blue * exponent;
  83001. }
  83002. else {
  83003. float32array[index + 0] = 0;
  83004. float32array[index + 1] = 0;
  83005. float32array[index + 2] = 0;
  83006. }
  83007. };
  83008. HDRTools.readStringLine = function (uint8array, startIndex) {
  83009. var line = "";
  83010. var character = "";
  83011. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83012. character = String.fromCharCode(uint8array[i]);
  83013. if (character == "\n") {
  83014. break;
  83015. }
  83016. line += character;
  83017. }
  83018. return line;
  83019. };
  83020. /**
  83021. * Reads header information from an RGBE texture stored in a native array.
  83022. * More information on this format are available here:
  83023. * https://en.wikipedia.org/wiki/RGBE_image_format
  83024. *
  83025. * @param uint8array The binary file stored in native array.
  83026. * @return The header information.
  83027. */
  83028. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83029. var height = 0;
  83030. var width = 0;
  83031. var line = this.readStringLine(uint8array, 0);
  83032. if (line[0] != '#' || line[1] != '?') {
  83033. throw "Bad HDR Format.";
  83034. }
  83035. var endOfHeader = false;
  83036. var findFormat = false;
  83037. var lineIndex = 0;
  83038. do {
  83039. lineIndex += (line.length + 1);
  83040. line = this.readStringLine(uint8array, lineIndex);
  83041. if (line == "FORMAT=32-bit_rle_rgbe") {
  83042. findFormat = true;
  83043. }
  83044. else if (line.length == 0) {
  83045. endOfHeader = true;
  83046. }
  83047. } while (!endOfHeader);
  83048. if (!findFormat) {
  83049. throw "HDR Bad header format, unsupported FORMAT";
  83050. }
  83051. lineIndex += (line.length + 1);
  83052. line = this.readStringLine(uint8array, lineIndex);
  83053. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83054. var match = sizeRegexp.exec(line);
  83055. // TODO. Support +Y and -X if needed.
  83056. if (!match || match.length < 3) {
  83057. throw "HDR Bad header format, no size";
  83058. }
  83059. width = parseInt(match[2]);
  83060. height = parseInt(match[1]);
  83061. if (width < 8 || width > 0x7fff) {
  83062. throw "HDR Bad header format, unsupported size";
  83063. }
  83064. lineIndex += (line.length + 1);
  83065. return {
  83066. height: height,
  83067. width: width,
  83068. dataPosition: lineIndex
  83069. };
  83070. };
  83071. /**
  83072. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83073. * This RGBE texture needs to store the information as a panorama.
  83074. *
  83075. * More information on this format are available here:
  83076. * https://en.wikipedia.org/wiki/RGBE_image_format
  83077. *
  83078. * @param buffer The binary file stored in an array buffer.
  83079. * @param size The expected size of the extracted cubemap.
  83080. * @return The Cube Map information.
  83081. */
  83082. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83083. var uint8array = new Uint8Array(buffer);
  83084. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83085. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83086. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83087. return cubeMapData;
  83088. };
  83089. /**
  83090. * Returns the pixels data extracted from an RGBE texture.
  83091. * This pixels will be stored left to right up to down in the R G B order in one array.
  83092. *
  83093. * More information on this format are available here:
  83094. * https://en.wikipedia.org/wiki/RGBE_image_format
  83095. *
  83096. * @param uint8array The binary file stored in an array buffer.
  83097. * @param hdrInfo The header information of the file.
  83098. * @return The pixels data in RGB right to left up to down order.
  83099. */
  83100. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83101. // Keep for multi format supports.
  83102. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83103. };
  83104. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83105. var num_scanlines = hdrInfo.height;
  83106. var scanline_width = hdrInfo.width;
  83107. var a, b, c, d, count;
  83108. var dataIndex = hdrInfo.dataPosition;
  83109. var index = 0, endIndex = 0, i = 0;
  83110. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83111. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83112. // 3 channels of 4 bytes per pixel in float.
  83113. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83114. var resultArray = new Float32Array(resultBuffer);
  83115. // read in each successive scanline
  83116. while (num_scanlines > 0) {
  83117. a = uint8array[dataIndex++];
  83118. b = uint8array[dataIndex++];
  83119. c = uint8array[dataIndex++];
  83120. d = uint8array[dataIndex++];
  83121. if (a != 2 || b != 2 || (c & 0x80)) {
  83122. // this file is not run length encoded
  83123. throw "HDR Bad header format, not RLE";
  83124. }
  83125. if (((c << 8) | d) != scanline_width) {
  83126. throw "HDR Bad header format, wrong scan line width";
  83127. }
  83128. index = 0;
  83129. // read each of the four channels for the scanline into the buffer
  83130. for (i = 0; i < 4; i++) {
  83131. endIndex = (i + 1) * scanline_width;
  83132. while (index < endIndex) {
  83133. a = uint8array[dataIndex++];
  83134. b = uint8array[dataIndex++];
  83135. if (a > 128) {
  83136. // a run of the same value
  83137. count = a - 128;
  83138. if ((count == 0) || (count > endIndex - index)) {
  83139. throw "HDR Bad Format, bad scanline data (run)";
  83140. }
  83141. while (count-- > 0) {
  83142. scanLineArray[index++] = b;
  83143. }
  83144. }
  83145. else {
  83146. // a non-run
  83147. count = a;
  83148. if ((count == 0) || (count > endIndex - index)) {
  83149. throw "HDR Bad Format, bad scanline data (non-run)";
  83150. }
  83151. scanLineArray[index++] = b;
  83152. if (--count > 0) {
  83153. for (var j = 0; j < count; j++) {
  83154. scanLineArray[index++] = uint8array[dataIndex++];
  83155. }
  83156. }
  83157. }
  83158. }
  83159. }
  83160. // now convert data from buffer into floats
  83161. for (i = 0; i < scanline_width; i++) {
  83162. a = scanLineArray[i];
  83163. b = scanLineArray[i + scanline_width];
  83164. c = scanLineArray[i + 2 * scanline_width];
  83165. d = scanLineArray[i + 3 * scanline_width];
  83166. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83167. }
  83168. num_scanlines--;
  83169. }
  83170. return resultArray;
  83171. };
  83172. return HDRTools;
  83173. }());
  83174. BABYLON.HDRTools = HDRTools;
  83175. })(BABYLON || (BABYLON = {}));
  83176. //# sourceMappingURL=babylon.hdr.js.map
  83177. var BABYLON;
  83178. (function (BABYLON) {
  83179. /**
  83180. * This represents a texture coming from an HDR input.
  83181. *
  83182. * The only supported format is currently panorama picture stored in RGBE format.
  83183. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83184. */
  83185. var HDRCubeTexture = /** @class */ (function (_super) {
  83186. __extends(HDRCubeTexture, _super);
  83187. /**
  83188. * Instantiates an HDRTexture from the following parameters.
  83189. *
  83190. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83191. * @param scene The scene the texture will be used in
  83192. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83193. * @param noMipmap Forces to not generate the mipmap if true
  83194. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83195. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  83196. * @param reserved Reserved flag for internal use.
  83197. */
  83198. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83199. if (noMipmap === void 0) { noMipmap = false; }
  83200. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83201. if (gammaSpace === void 0) { gammaSpace = false; }
  83202. if (reserved === void 0) { reserved = false; }
  83203. if (onLoad === void 0) { onLoad = null; }
  83204. if (onError === void 0) { onError = null; }
  83205. var _this = _super.call(this, scene) || this;
  83206. _this._generateHarmonics = true;
  83207. _this._onLoad = null;
  83208. _this._onError = null;
  83209. /**
  83210. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83211. */
  83212. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83213. _this._isBlocking = true;
  83214. _this._rotationY = 0;
  83215. /**
  83216. * Gets or sets the center of the bounding box associated with the cube texture
  83217. * It must define where the camera used to render the texture was set
  83218. */
  83219. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83220. if (!url) {
  83221. return _this;
  83222. }
  83223. _this.name = url;
  83224. _this.url = url;
  83225. _this.hasAlpha = false;
  83226. _this.isCube = true;
  83227. _this._textureMatrix = BABYLON.Matrix.Identity();
  83228. _this._onLoad = onLoad;
  83229. _this._onError = onError;
  83230. _this.gammaSpace = gammaSpace;
  83231. _this._noMipmap = noMipmap;
  83232. _this._size = size;
  83233. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83234. if (!_this._texture) {
  83235. if (!scene.useDelayedTextureLoading) {
  83236. _this.loadTexture();
  83237. }
  83238. else {
  83239. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83240. }
  83241. }
  83242. return _this;
  83243. }
  83244. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83245. /**
  83246. * Gets wether or not the texture is blocking during loading.
  83247. */
  83248. get: function () {
  83249. return this._isBlocking;
  83250. },
  83251. /**
  83252. * Sets wether or not the texture is blocking during loading.
  83253. */
  83254. set: function (value) {
  83255. this._isBlocking = value;
  83256. },
  83257. enumerable: true,
  83258. configurable: true
  83259. });
  83260. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83261. /**
  83262. * Gets texture matrix rotation angle around Y axis radians.
  83263. */
  83264. get: function () {
  83265. return this._rotationY;
  83266. },
  83267. /**
  83268. * Sets texture matrix rotation angle around Y axis in radians.
  83269. */
  83270. set: function (value) {
  83271. this._rotationY = value;
  83272. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83273. },
  83274. enumerable: true,
  83275. configurable: true
  83276. });
  83277. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83278. get: function () {
  83279. return this._boundingBoxSize;
  83280. },
  83281. /**
  83282. * Gets or sets the size of the bounding box associated with the cube texture
  83283. * When defined, the cubemap will switch to local mode
  83284. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83285. * @example https://www.babylonjs-playground.com/#RNASML
  83286. */
  83287. set: function (value) {
  83288. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83289. return;
  83290. }
  83291. this._boundingBoxSize = value;
  83292. var scene = this.getScene();
  83293. if (scene) {
  83294. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83295. }
  83296. },
  83297. enumerable: true,
  83298. configurable: true
  83299. });
  83300. /**
  83301. * Occurs when the file is raw .hdr file.
  83302. */
  83303. HDRCubeTexture.prototype.loadTexture = function () {
  83304. var _this = this;
  83305. var callback = function (buffer) {
  83306. _this.lodGenerationOffset = 0.0;
  83307. _this.lodGenerationScale = 0.8;
  83308. var scene = _this.getScene();
  83309. if (!scene) {
  83310. return null;
  83311. }
  83312. // Extract the raw linear data.
  83313. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83314. // Generate harmonics if needed.
  83315. if (_this._generateHarmonics) {
  83316. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83317. _this.sphericalPolynomial = sphericalPolynomial;
  83318. }
  83319. var results = [];
  83320. var byteArray = null;
  83321. // Push each faces.
  83322. for (var j = 0; j < 6; j++) {
  83323. // Create uintarray fallback.
  83324. if (!scene.getEngine().getCaps().textureFloat) {
  83325. // 3 channels of 1 bytes per pixel in bytes.
  83326. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83327. byteArray = new Uint8Array(byteBuffer);
  83328. }
  83329. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83330. // If special cases.
  83331. if (_this.gammaSpace || byteArray) {
  83332. for (var i = 0; i < _this._size * _this._size; i++) {
  83333. // Put in gamma space if requested.
  83334. if (_this.gammaSpace) {
  83335. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83336. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83337. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83338. }
  83339. // Convert to int texture for fallback.
  83340. if (byteArray) {
  83341. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83342. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83343. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83344. // May use luminance instead if the result is not accurate.
  83345. var max = Math.max(Math.max(r, g), b);
  83346. if (max > 255) {
  83347. var scale = 255 / max;
  83348. r *= scale;
  83349. g *= scale;
  83350. b *= scale;
  83351. }
  83352. byteArray[(i * 3) + 0] = r;
  83353. byteArray[(i * 3) + 1] = g;
  83354. byteArray[(i * 3) + 2] = b;
  83355. }
  83356. }
  83357. }
  83358. if (byteArray) {
  83359. results.push(byteArray);
  83360. }
  83361. else {
  83362. results.push(dataFace);
  83363. }
  83364. }
  83365. return results;
  83366. };
  83367. var scene = this.getScene();
  83368. if (scene) {
  83369. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  83370. }
  83371. };
  83372. HDRCubeTexture.prototype.clone = function () {
  83373. var scene = this.getScene();
  83374. if (!scene) {
  83375. return this;
  83376. }
  83377. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83378. // Base texture
  83379. newTexture.level = this.level;
  83380. newTexture.wrapU = this.wrapU;
  83381. newTexture.wrapV = this.wrapV;
  83382. newTexture.coordinatesIndex = this.coordinatesIndex;
  83383. newTexture.coordinatesMode = this.coordinatesMode;
  83384. return newTexture;
  83385. };
  83386. // Methods
  83387. HDRCubeTexture.prototype.delayLoad = function () {
  83388. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83389. return;
  83390. }
  83391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83392. this._texture = this._getFromCache(this.url, this._noMipmap);
  83393. if (!this._texture) {
  83394. this.loadTexture();
  83395. }
  83396. };
  83397. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83398. return this._textureMatrix;
  83399. };
  83400. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83401. this._textureMatrix = value;
  83402. };
  83403. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83404. var texture = null;
  83405. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83406. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83407. texture.name = parsedTexture.name;
  83408. texture.hasAlpha = parsedTexture.hasAlpha;
  83409. texture.level = parsedTexture.level;
  83410. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83411. texture.isBlocking = parsedTexture.isBlocking;
  83412. }
  83413. if (texture) {
  83414. if (parsedTexture.boundingBoxPosition) {
  83415. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83416. }
  83417. if (parsedTexture.boundingBoxSize) {
  83418. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83419. }
  83420. if (parsedTexture.rotationY) {
  83421. texture.rotationY = parsedTexture.rotationY;
  83422. }
  83423. }
  83424. return texture;
  83425. };
  83426. HDRCubeTexture.prototype.serialize = function () {
  83427. if (!this.name) {
  83428. return null;
  83429. }
  83430. var serializationObject = {};
  83431. serializationObject.name = this.name;
  83432. serializationObject.hasAlpha = this.hasAlpha;
  83433. serializationObject.isCube = true;
  83434. serializationObject.level = this.level;
  83435. serializationObject.size = this._size;
  83436. serializationObject.coordinatesMode = this.coordinatesMode;
  83437. serializationObject.useInGammaSpace = this.gammaSpace;
  83438. serializationObject.generateHarmonics = this._generateHarmonics;
  83439. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83440. serializationObject.noMipmap = this._noMipmap;
  83441. serializationObject.isBlocking = this._isBlocking;
  83442. serializationObject.rotationY = this._rotationY;
  83443. return serializationObject;
  83444. };
  83445. HDRCubeTexture._facesMapping = [
  83446. "right",
  83447. "left",
  83448. "up",
  83449. "down",
  83450. "front",
  83451. "back"
  83452. ];
  83453. return HDRCubeTexture;
  83454. }(BABYLON.BaseTexture));
  83455. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83456. })(BABYLON || (BABYLON = {}));
  83457. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83458. var BABYLON;
  83459. (function (BABYLON) {
  83460. /**
  83461. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  83462. */
  83463. var PanoramaToCubeMapTools = /** @class */ (function () {
  83464. function PanoramaToCubeMapTools() {
  83465. }
  83466. /**
  83467. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  83468. *
  83469. * @param float32Array The source data.
  83470. * @param inputWidth The width of the input panorama.
  83471. * @param inputhHeight The height of the input panorama.
  83472. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  83473. * @return The cubemap data
  83474. */
  83475. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  83476. if (!float32Array) {
  83477. throw "ConvertPanoramaToCubemap: input cannot be null";
  83478. }
  83479. if (float32Array.length != inputWidth * inputHeight * 3) {
  83480. throw "ConvertPanoramaToCubemap: input size is wrong";
  83481. }
  83482. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  83483. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  83484. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  83485. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  83486. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  83487. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  83488. return {
  83489. front: textureFront,
  83490. back: textureBack,
  83491. left: textureLeft,
  83492. right: textureRight,
  83493. up: textureUp,
  83494. down: textureDown,
  83495. size: size,
  83496. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  83497. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  83498. gammaSpace: false,
  83499. };
  83500. };
  83501. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  83502. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  83503. var textureArray = new Float32Array(buffer);
  83504. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  83505. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  83506. var dy = 1 / texSize;
  83507. var fy = 0;
  83508. for (var y = 0; y < texSize; y++) {
  83509. var xv1 = faceData[0];
  83510. var xv2 = faceData[2];
  83511. for (var x = 0; x < texSize; x++) {
  83512. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  83513. v.normalize();
  83514. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  83515. // 3 channels per pixels
  83516. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  83517. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  83518. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  83519. xv1 = xv1.add(rotDX1);
  83520. xv2 = xv2.add(rotDX2);
  83521. }
  83522. fy += dy;
  83523. }
  83524. return textureArray;
  83525. };
  83526. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  83527. var theta = Math.atan2(vDir.z, vDir.x);
  83528. var phi = Math.acos(vDir.y);
  83529. while (theta < -Math.PI)
  83530. theta += 2 * Math.PI;
  83531. while (theta > Math.PI)
  83532. theta -= 2 * Math.PI;
  83533. var dx = theta / Math.PI;
  83534. var dy = phi / Math.PI;
  83535. // recenter.
  83536. dx = dx * 0.5 + 0.5;
  83537. var px = Math.round(dx * inputWidth);
  83538. if (px < 0)
  83539. px = 0;
  83540. else if (px >= inputWidth)
  83541. px = inputWidth - 1;
  83542. var py = Math.round(dy * inputHeight);
  83543. if (py < 0)
  83544. py = 0;
  83545. else if (py >= inputHeight)
  83546. py = inputHeight - 1;
  83547. var inputY = (inputHeight - py - 1);
  83548. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  83549. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  83550. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  83551. return {
  83552. r: r,
  83553. g: g,
  83554. b: b
  83555. };
  83556. };
  83557. PanoramaToCubeMapTools.FACE_FRONT = [
  83558. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83559. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83560. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83561. new BABYLON.Vector3(1.0, 1.0, -1.0)
  83562. ];
  83563. PanoramaToCubeMapTools.FACE_BACK = [
  83564. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83565. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83566. new BABYLON.Vector3(1.0, 1.0, 1.0),
  83567. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  83568. ];
  83569. PanoramaToCubeMapTools.FACE_RIGHT = [
  83570. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83571. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83572. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83573. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83574. ];
  83575. PanoramaToCubeMapTools.FACE_LEFT = [
  83576. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83577. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83578. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83579. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  83580. ];
  83581. PanoramaToCubeMapTools.FACE_DOWN = [
  83582. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83583. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83584. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83585. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83586. ];
  83587. PanoramaToCubeMapTools.FACE_UP = [
  83588. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83589. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83590. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83591. new BABYLON.Vector3(1.0, -1.0, -1.0)
  83592. ];
  83593. return PanoramaToCubeMapTools;
  83594. }());
  83595. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  83596. })(BABYLON || (BABYLON = {}));
  83597. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  83598. var BABYLON;
  83599. (function (BABYLON) {
  83600. var IndexedVector2 = /** @class */ (function (_super) {
  83601. __extends(IndexedVector2, _super);
  83602. function IndexedVector2(original, index) {
  83603. var _this = _super.call(this, original.x, original.y) || this;
  83604. _this.index = index;
  83605. return _this;
  83606. }
  83607. return IndexedVector2;
  83608. }(BABYLON.Vector2));
  83609. var PolygonPoints = /** @class */ (function () {
  83610. function PolygonPoints() {
  83611. this.elements = new Array();
  83612. }
  83613. PolygonPoints.prototype.add = function (originalPoints) {
  83614. var _this = this;
  83615. var result = new Array();
  83616. originalPoints.forEach(function (point) {
  83617. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83618. var newPoint = new IndexedVector2(point, _this.elements.length);
  83619. result.push(newPoint);
  83620. _this.elements.push(newPoint);
  83621. }
  83622. });
  83623. return result;
  83624. };
  83625. PolygonPoints.prototype.computeBounds = function () {
  83626. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83627. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83628. this.elements.forEach(function (point) {
  83629. // x
  83630. if (point.x < lmin.x) {
  83631. lmin.x = point.x;
  83632. }
  83633. else if (point.x > lmax.x) {
  83634. lmax.x = point.x;
  83635. }
  83636. // y
  83637. if (point.y < lmin.y) {
  83638. lmin.y = point.y;
  83639. }
  83640. else if (point.y > lmax.y) {
  83641. lmax.y = point.y;
  83642. }
  83643. });
  83644. return {
  83645. min: lmin,
  83646. max: lmax,
  83647. width: lmax.x - lmin.x,
  83648. height: lmax.y - lmin.y
  83649. };
  83650. };
  83651. return PolygonPoints;
  83652. }());
  83653. var Polygon = /** @class */ (function () {
  83654. function Polygon() {
  83655. }
  83656. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83657. return [
  83658. new BABYLON.Vector2(xmin, ymin),
  83659. new BABYLON.Vector2(xmax, ymin),
  83660. new BABYLON.Vector2(xmax, ymax),
  83661. new BABYLON.Vector2(xmin, ymax)
  83662. ];
  83663. };
  83664. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83665. if (cx === void 0) { cx = 0; }
  83666. if (cy === void 0) { cy = 0; }
  83667. if (numberOfSides === void 0) { numberOfSides = 32; }
  83668. var result = new Array();
  83669. var angle = 0;
  83670. var increment = (Math.PI * 2) / numberOfSides;
  83671. for (var i = 0; i < numberOfSides; i++) {
  83672. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83673. angle -= increment;
  83674. }
  83675. return result;
  83676. };
  83677. Polygon.Parse = function (input) {
  83678. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83679. var i, result = [];
  83680. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83681. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83682. }
  83683. return result;
  83684. };
  83685. Polygon.StartingAt = function (x, y) {
  83686. return BABYLON.Path2.StartingAt(x, y);
  83687. };
  83688. return Polygon;
  83689. }());
  83690. BABYLON.Polygon = Polygon;
  83691. var PolygonMeshBuilder = /** @class */ (function () {
  83692. function PolygonMeshBuilder(name, contours, scene) {
  83693. this._points = new PolygonPoints();
  83694. this._outlinepoints = new PolygonPoints();
  83695. this._holes = new Array();
  83696. this._epoints = new Array();
  83697. this._eholes = new Array();
  83698. this._name = name;
  83699. this._scene = scene;
  83700. var points;
  83701. if (contours instanceof BABYLON.Path2) {
  83702. points = contours.getPoints();
  83703. }
  83704. else {
  83705. points = contours;
  83706. }
  83707. this._addToepoint(points);
  83708. this._points.add(points);
  83709. this._outlinepoints.add(points);
  83710. if (typeof earcut === 'undefined') {
  83711. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83712. }
  83713. }
  83714. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83715. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83716. var p = points_1[_i];
  83717. this._epoints.push(p.x, p.y);
  83718. }
  83719. };
  83720. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83721. this._points.add(hole);
  83722. var holepoints = new PolygonPoints();
  83723. holepoints.add(hole);
  83724. this._holes.push(holepoints);
  83725. this._eholes.push(this._epoints.length / 2);
  83726. this._addToepoint(hole);
  83727. return this;
  83728. };
  83729. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83730. var _this = this;
  83731. if (updatable === void 0) { updatable = false; }
  83732. if (depth === void 0) { depth = 0; }
  83733. var result = new BABYLON.Mesh(this._name, this._scene);
  83734. var normals = new Array();
  83735. var positions = new Array();
  83736. var uvs = new Array();
  83737. var bounds = this._points.computeBounds();
  83738. this._points.elements.forEach(function (p) {
  83739. normals.push(0, 1.0, 0);
  83740. positions.push(p.x, 0, p.y);
  83741. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83742. });
  83743. var indices = new Array();
  83744. var res = earcut(this._epoints, this._eholes, 2);
  83745. for (var i = 0; i < res.length; i++) {
  83746. indices.push(res[i]);
  83747. }
  83748. if (depth > 0) {
  83749. var positionscount = (positions.length / 3); //get the current pointcount
  83750. this._points.elements.forEach(function (p) {
  83751. normals.push(0, -1.0, 0);
  83752. positions.push(p.x, -depth, p.y);
  83753. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83754. });
  83755. var totalCount = indices.length;
  83756. for (var i = 0; i < totalCount; i += 3) {
  83757. var i0 = indices[i + 0];
  83758. var i1 = indices[i + 1];
  83759. var i2 = indices[i + 2];
  83760. indices.push(i2 + positionscount);
  83761. indices.push(i1 + positionscount);
  83762. indices.push(i0 + positionscount);
  83763. }
  83764. //Add the sides
  83765. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83766. this._holes.forEach(function (hole) {
  83767. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83768. });
  83769. }
  83770. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83771. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83772. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83773. result.setIndices(indices);
  83774. return result;
  83775. };
  83776. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83777. var StartIndex = positions.length / 3;
  83778. var ulength = 0;
  83779. for (var i = 0; i < points.elements.length; i++) {
  83780. var p = points.elements[i];
  83781. var p1;
  83782. if ((i + 1) > points.elements.length - 1) {
  83783. p1 = points.elements[0];
  83784. }
  83785. else {
  83786. p1 = points.elements[i + 1];
  83787. }
  83788. positions.push(p.x, 0, p.y);
  83789. positions.push(p.x, -depth, p.y);
  83790. positions.push(p1.x, 0, p1.y);
  83791. positions.push(p1.x, -depth, p1.y);
  83792. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83793. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83794. var v3 = v2.subtract(v1);
  83795. var v4 = new BABYLON.Vector3(0, 1, 0);
  83796. var vn = BABYLON.Vector3.Cross(v3, v4);
  83797. vn = vn.normalize();
  83798. uvs.push(ulength / bounds.width, 0);
  83799. uvs.push(ulength / bounds.width, 1);
  83800. ulength += v3.length();
  83801. uvs.push((ulength / bounds.width), 0);
  83802. uvs.push((ulength / bounds.width), 1);
  83803. if (!flip) {
  83804. normals.push(-vn.x, -vn.y, -vn.z);
  83805. normals.push(-vn.x, -vn.y, -vn.z);
  83806. normals.push(-vn.x, -vn.y, -vn.z);
  83807. normals.push(-vn.x, -vn.y, -vn.z);
  83808. indices.push(StartIndex);
  83809. indices.push(StartIndex + 1);
  83810. indices.push(StartIndex + 2);
  83811. indices.push(StartIndex + 1);
  83812. indices.push(StartIndex + 3);
  83813. indices.push(StartIndex + 2);
  83814. }
  83815. else {
  83816. normals.push(vn.x, vn.y, vn.z);
  83817. normals.push(vn.x, vn.y, vn.z);
  83818. normals.push(vn.x, vn.y, vn.z);
  83819. normals.push(vn.x, vn.y, vn.z);
  83820. indices.push(StartIndex);
  83821. indices.push(StartIndex + 2);
  83822. indices.push(StartIndex + 1);
  83823. indices.push(StartIndex + 1);
  83824. indices.push(StartIndex + 2);
  83825. indices.push(StartIndex + 3);
  83826. }
  83827. StartIndex += 4;
  83828. }
  83829. ;
  83830. };
  83831. return PolygonMeshBuilder;
  83832. }());
  83833. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83834. })(BABYLON || (BABYLON = {}));
  83835. //# sourceMappingURL=babylon.polygonMesh.js.map
  83836. var BABYLON;
  83837. (function (BABYLON) {
  83838. // Unique ID when we import meshes from Babylon to CSG
  83839. var currentCSGMeshId = 0;
  83840. // # class Vertex
  83841. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83842. // one to provide additional features like texture coordinates and vertex
  83843. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83844. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83845. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83846. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83847. // is not used anywhere else.
  83848. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83849. var Vertex = /** @class */ (function () {
  83850. function Vertex(pos, normal, uv) {
  83851. this.pos = pos;
  83852. this.normal = normal;
  83853. this.uv = uv;
  83854. }
  83855. Vertex.prototype.clone = function () {
  83856. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83857. };
  83858. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83859. // orientation of a polygon is flipped.
  83860. Vertex.prototype.flip = function () {
  83861. this.normal = this.normal.scale(-1);
  83862. };
  83863. // Create a new vertex between this vertex and `other` by linearly
  83864. // interpolating all properties using a parameter of `t`. Subclasses should
  83865. // override this to interpolate additional properties.
  83866. Vertex.prototype.interpolate = function (other, t) {
  83867. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  83868. };
  83869. return Vertex;
  83870. }());
  83871. // # class Plane
  83872. // Represents a plane in 3D space.
  83873. var Plane = /** @class */ (function () {
  83874. function Plane(normal, w) {
  83875. this.normal = normal;
  83876. this.w = w;
  83877. }
  83878. Plane.FromPoints = function (a, b, c) {
  83879. var v0 = c.subtract(a);
  83880. var v1 = b.subtract(a);
  83881. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83882. return null;
  83883. }
  83884. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83885. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83886. };
  83887. Plane.prototype.clone = function () {
  83888. return new Plane(this.normal.clone(), this.w);
  83889. };
  83890. Plane.prototype.flip = function () {
  83891. this.normal.scaleInPlace(-1);
  83892. this.w = -this.w;
  83893. };
  83894. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83895. // fragments in the appropriate lists. Coplanar polygons go into either
  83896. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83897. // respect to this plane. Polygons in front or in back of this plane go into
  83898. // either `front` or `back`.
  83899. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83900. var COPLANAR = 0;
  83901. var FRONT = 1;
  83902. var BACK = 2;
  83903. var SPANNING = 3;
  83904. // Classify each point as well as the entire polygon into one of the above
  83905. // four classes.
  83906. var polygonType = 0;
  83907. var types = [];
  83908. var i;
  83909. var t;
  83910. for (i = 0; i < polygon.vertices.length; i++) {
  83911. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83912. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83913. polygonType |= type;
  83914. types.push(type);
  83915. }
  83916. // Put the polygon in the correct list, splitting it when necessary.
  83917. switch (polygonType) {
  83918. case COPLANAR:
  83919. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83920. break;
  83921. case FRONT:
  83922. front.push(polygon);
  83923. break;
  83924. case BACK:
  83925. back.push(polygon);
  83926. break;
  83927. case SPANNING:
  83928. var f = [], b = [];
  83929. for (i = 0; i < polygon.vertices.length; i++) {
  83930. var j = (i + 1) % polygon.vertices.length;
  83931. var ti = types[i], tj = types[j];
  83932. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83933. if (ti !== BACK)
  83934. f.push(vi);
  83935. if (ti !== FRONT)
  83936. b.push(ti !== BACK ? vi.clone() : vi);
  83937. if ((ti | tj) === SPANNING) {
  83938. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83939. var v = vi.interpolate(vj, t);
  83940. f.push(v);
  83941. b.push(v.clone());
  83942. }
  83943. }
  83944. var poly;
  83945. if (f.length >= 3) {
  83946. poly = new Polygon(f, polygon.shared);
  83947. if (poly.plane)
  83948. front.push(poly);
  83949. }
  83950. if (b.length >= 3) {
  83951. poly = new Polygon(b, polygon.shared);
  83952. if (poly.plane)
  83953. back.push(poly);
  83954. }
  83955. break;
  83956. }
  83957. };
  83958. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83959. // point is on the plane.
  83960. Plane.EPSILON = 1e-5;
  83961. return Plane;
  83962. }());
  83963. // # class Polygon
  83964. // Represents a convex polygon. The vertices used to initialize a polygon must
  83965. // be coplanar and form a convex loop.
  83966. //
  83967. // Each convex polygon has a `shared` property, which is shared between all
  83968. // polygons that are clones of each other or were split from the same polygon.
  83969. // This can be used to define per-polygon properties (such as surface color).
  83970. var Polygon = /** @class */ (function () {
  83971. function Polygon(vertices, shared) {
  83972. this.vertices = vertices;
  83973. this.shared = shared;
  83974. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83975. }
  83976. Polygon.prototype.clone = function () {
  83977. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83978. return new Polygon(vertices, this.shared);
  83979. };
  83980. Polygon.prototype.flip = function () {
  83981. this.vertices.reverse().map(function (v) { v.flip(); });
  83982. this.plane.flip();
  83983. };
  83984. return Polygon;
  83985. }());
  83986. // # class Node
  83987. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83988. // by picking a polygon to split along. That polygon (and all other coplanar
  83989. // polygons) are added directly to that node and the other polygons are added to
  83990. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83991. // no distinction between internal and leaf nodes.
  83992. var Node = /** @class */ (function () {
  83993. function Node(polygons) {
  83994. this.plane = null;
  83995. this.front = null;
  83996. this.back = null;
  83997. this.polygons = new Array();
  83998. if (polygons) {
  83999. this.build(polygons);
  84000. }
  84001. }
  84002. Node.prototype.clone = function () {
  84003. var node = new Node();
  84004. node.plane = this.plane && this.plane.clone();
  84005. node.front = this.front && this.front.clone();
  84006. node.back = this.back && this.back.clone();
  84007. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84008. return node;
  84009. };
  84010. // Convert solid space to empty space and empty space to solid space.
  84011. Node.prototype.invert = function () {
  84012. for (var i = 0; i < this.polygons.length; i++) {
  84013. this.polygons[i].flip();
  84014. }
  84015. if (this.plane) {
  84016. this.plane.flip();
  84017. }
  84018. if (this.front) {
  84019. this.front.invert();
  84020. }
  84021. if (this.back) {
  84022. this.back.invert();
  84023. }
  84024. var temp = this.front;
  84025. this.front = this.back;
  84026. this.back = temp;
  84027. };
  84028. // Recursively remove all polygons in `polygons` that are inside this BSP
  84029. // tree.
  84030. Node.prototype.clipPolygons = function (polygons) {
  84031. if (!this.plane)
  84032. return polygons.slice();
  84033. var front = new Array(), back = new Array();
  84034. for (var i = 0; i < polygons.length; i++) {
  84035. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84036. }
  84037. if (this.front) {
  84038. front = this.front.clipPolygons(front);
  84039. }
  84040. if (this.back) {
  84041. back = this.back.clipPolygons(back);
  84042. }
  84043. else {
  84044. back = [];
  84045. }
  84046. return front.concat(back);
  84047. };
  84048. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84049. // `bsp`.
  84050. Node.prototype.clipTo = function (bsp) {
  84051. this.polygons = bsp.clipPolygons(this.polygons);
  84052. if (this.front)
  84053. this.front.clipTo(bsp);
  84054. if (this.back)
  84055. this.back.clipTo(bsp);
  84056. };
  84057. // Return a list of all polygons in this BSP tree.
  84058. Node.prototype.allPolygons = function () {
  84059. var polygons = this.polygons.slice();
  84060. if (this.front)
  84061. polygons = polygons.concat(this.front.allPolygons());
  84062. if (this.back)
  84063. polygons = polygons.concat(this.back.allPolygons());
  84064. return polygons;
  84065. };
  84066. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84067. // new polygons are filtered down to the bottom of the tree and become new
  84068. // nodes there. Each set of polygons is partitioned using the first polygon
  84069. // (no heuristic is used to pick a good split).
  84070. Node.prototype.build = function (polygons) {
  84071. if (!polygons.length)
  84072. return;
  84073. if (!this.plane)
  84074. this.plane = polygons[0].plane.clone();
  84075. var front = new Array(), back = new Array();
  84076. for (var i = 0; i < polygons.length; i++) {
  84077. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84078. }
  84079. if (front.length) {
  84080. if (!this.front)
  84081. this.front = new Node();
  84082. this.front.build(front);
  84083. }
  84084. if (back.length) {
  84085. if (!this.back)
  84086. this.back = new Node();
  84087. this.back.build(back);
  84088. }
  84089. };
  84090. return Node;
  84091. }());
  84092. var CSG = /** @class */ (function () {
  84093. function CSG() {
  84094. this.polygons = new Array();
  84095. }
  84096. // Convert BABYLON.Mesh to BABYLON.CSG
  84097. CSG.FromMesh = function (mesh) {
  84098. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84099. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84100. if (mesh instanceof BABYLON.Mesh) {
  84101. mesh.computeWorldMatrix(true);
  84102. matrix = mesh.getWorldMatrix();
  84103. meshPosition = mesh.position.clone();
  84104. meshRotation = mesh.rotation.clone();
  84105. if (mesh.rotationQuaternion) {
  84106. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84107. }
  84108. meshScaling = mesh.scaling.clone();
  84109. }
  84110. else {
  84111. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84112. }
  84113. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84114. var subMeshes = mesh.subMeshes;
  84115. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84116. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84117. vertices = [];
  84118. for (var j = 0; j < 3; j++) {
  84119. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84120. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84121. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84122. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84123. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84124. vertex = new Vertex(position, normal, uv);
  84125. vertices.push(vertex);
  84126. }
  84127. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84128. // To handle the case of degenerated triangle
  84129. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84130. if (polygon.plane)
  84131. polygons.push(polygon);
  84132. }
  84133. }
  84134. var csg = CSG.FromPolygons(polygons);
  84135. csg.matrix = matrix;
  84136. csg.position = meshPosition;
  84137. csg.rotation = meshRotation;
  84138. csg.scaling = meshScaling;
  84139. csg.rotationQuaternion = meshRotationQuaternion;
  84140. currentCSGMeshId++;
  84141. return csg;
  84142. };
  84143. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84144. CSG.FromPolygons = function (polygons) {
  84145. var csg = new CSG();
  84146. csg.polygons = polygons;
  84147. return csg;
  84148. };
  84149. CSG.prototype.clone = function () {
  84150. var csg = new CSG();
  84151. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84152. csg.copyTransformAttributes(this);
  84153. return csg;
  84154. };
  84155. CSG.prototype.union = function (csg) {
  84156. var a = new Node(this.clone().polygons);
  84157. var b = new Node(csg.clone().polygons);
  84158. a.clipTo(b);
  84159. b.clipTo(a);
  84160. b.invert();
  84161. b.clipTo(a);
  84162. b.invert();
  84163. a.build(b.allPolygons());
  84164. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84165. };
  84166. CSG.prototype.unionInPlace = function (csg) {
  84167. var a = new Node(this.polygons);
  84168. var b = new Node(csg.polygons);
  84169. a.clipTo(b);
  84170. b.clipTo(a);
  84171. b.invert();
  84172. b.clipTo(a);
  84173. b.invert();
  84174. a.build(b.allPolygons());
  84175. this.polygons = a.allPolygons();
  84176. };
  84177. CSG.prototype.subtract = function (csg) {
  84178. var a = new Node(this.clone().polygons);
  84179. var b = new Node(csg.clone().polygons);
  84180. a.invert();
  84181. a.clipTo(b);
  84182. b.clipTo(a);
  84183. b.invert();
  84184. b.clipTo(a);
  84185. b.invert();
  84186. a.build(b.allPolygons());
  84187. a.invert();
  84188. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84189. };
  84190. CSG.prototype.subtractInPlace = function (csg) {
  84191. var a = new Node(this.polygons);
  84192. var b = new Node(csg.polygons);
  84193. a.invert();
  84194. a.clipTo(b);
  84195. b.clipTo(a);
  84196. b.invert();
  84197. b.clipTo(a);
  84198. b.invert();
  84199. a.build(b.allPolygons());
  84200. a.invert();
  84201. this.polygons = a.allPolygons();
  84202. };
  84203. CSG.prototype.intersect = function (csg) {
  84204. var a = new Node(this.clone().polygons);
  84205. var b = new Node(csg.clone().polygons);
  84206. a.invert();
  84207. b.clipTo(a);
  84208. b.invert();
  84209. a.clipTo(b);
  84210. b.clipTo(a);
  84211. a.build(b.allPolygons());
  84212. a.invert();
  84213. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84214. };
  84215. CSG.prototype.intersectInPlace = function (csg) {
  84216. var a = new Node(this.polygons);
  84217. var b = new Node(csg.polygons);
  84218. a.invert();
  84219. b.clipTo(a);
  84220. b.invert();
  84221. a.clipTo(b);
  84222. b.clipTo(a);
  84223. a.build(b.allPolygons());
  84224. a.invert();
  84225. this.polygons = a.allPolygons();
  84226. };
  84227. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84228. // not modified.
  84229. CSG.prototype.inverse = function () {
  84230. var csg = this.clone();
  84231. csg.inverseInPlace();
  84232. return csg;
  84233. };
  84234. CSG.prototype.inverseInPlace = function () {
  84235. this.polygons.map(function (p) { p.flip(); });
  84236. };
  84237. // This is used to keep meshes transformations so they can be restored
  84238. // when we build back a Babylon Mesh
  84239. // NB : All CSG operations are performed in world coordinates
  84240. CSG.prototype.copyTransformAttributes = function (csg) {
  84241. this.matrix = csg.matrix;
  84242. this.position = csg.position;
  84243. this.rotation = csg.rotation;
  84244. this.scaling = csg.scaling;
  84245. this.rotationQuaternion = csg.rotationQuaternion;
  84246. return this;
  84247. };
  84248. // Build Raw mesh from CSG
  84249. // Coordinates here are in world space
  84250. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84251. var matrix = this.matrix.clone();
  84252. matrix.invert();
  84253. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  84254. if (keepSubMeshes) {
  84255. // Sort Polygons, since subMeshes are indices range
  84256. polygons.sort(function (a, b) {
  84257. if (a.shared.meshId === b.shared.meshId) {
  84258. return a.shared.subMeshId - b.shared.subMeshId;
  84259. }
  84260. else {
  84261. return a.shared.meshId - b.shared.meshId;
  84262. }
  84263. });
  84264. }
  84265. for (var i = 0, il = polygons.length; i < il; i++) {
  84266. polygon = polygons[i];
  84267. // Building SubMeshes
  84268. if (!subMesh_dict[polygon.shared.meshId]) {
  84269. subMesh_dict[polygon.shared.meshId] = {};
  84270. }
  84271. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84272. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84273. indexStart: +Infinity,
  84274. indexEnd: -Infinity,
  84275. materialIndex: polygon.shared.materialIndex
  84276. };
  84277. }
  84278. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84279. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84280. polygonIndices[0] = 0;
  84281. polygonIndices[1] = j - 1;
  84282. polygonIndices[2] = j;
  84283. for (var k = 0; k < 3; k++) {
  84284. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84285. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84286. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84287. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84288. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84289. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84290. // Check if 2 points can be merged
  84291. if (!(typeof vertex_idx !== 'undefined' &&
  84292. normals[vertex_idx * 3] === localNormal.x &&
  84293. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84294. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84295. uvs[vertex_idx * 2] === uv.x &&
  84296. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84297. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84298. uvs.push(uv.x, uv.y);
  84299. normals.push(normal.x, normal.y, normal.z);
  84300. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84301. }
  84302. indices.push(vertex_idx);
  84303. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84304. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84305. currentIndex++;
  84306. }
  84307. }
  84308. }
  84309. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84310. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84311. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84312. mesh.setIndices(indices, null);
  84313. if (keepSubMeshes) {
  84314. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84315. var materialIndexOffset = 0, materialMaxIndex;
  84316. mesh.subMeshes = new Array();
  84317. for (var m in subMesh_dict) {
  84318. materialMaxIndex = -1;
  84319. for (var sm in subMesh_dict[m]) {
  84320. subMesh_obj = subMesh_dict[m][sm];
  84321. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84322. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84323. }
  84324. materialIndexOffset += ++materialMaxIndex;
  84325. }
  84326. }
  84327. return mesh;
  84328. };
  84329. // Build Mesh from CSG taking material and transforms into account
  84330. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84331. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84332. mesh.material = material;
  84333. mesh.position.copyFrom(this.position);
  84334. mesh.rotation.copyFrom(this.rotation);
  84335. if (this.rotationQuaternion) {
  84336. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84337. }
  84338. mesh.scaling.copyFrom(this.scaling);
  84339. mesh.computeWorldMatrix(true);
  84340. return mesh;
  84341. };
  84342. return CSG;
  84343. }());
  84344. BABYLON.CSG = CSG;
  84345. })(BABYLON || (BABYLON = {}));
  84346. //# sourceMappingURL=babylon.csg.js.map
  84347. var BABYLON;
  84348. (function (BABYLON) {
  84349. var LensFlare = /** @class */ (function () {
  84350. function LensFlare(size, position, color, imgUrl, system) {
  84351. this.size = size;
  84352. this.position = position;
  84353. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84354. this.color = color || new BABYLON.Color3(1, 1, 1);
  84355. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84356. this._system = system;
  84357. system.lensFlares.push(this);
  84358. }
  84359. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84360. return new LensFlare(size, position, color, imgUrl, system);
  84361. };
  84362. LensFlare.prototype.dispose = function () {
  84363. if (this.texture) {
  84364. this.texture.dispose();
  84365. }
  84366. // Remove from scene
  84367. var index = this._system.lensFlares.indexOf(this);
  84368. this._system.lensFlares.splice(index, 1);
  84369. };
  84370. ;
  84371. return LensFlare;
  84372. }());
  84373. BABYLON.LensFlare = LensFlare;
  84374. })(BABYLON || (BABYLON = {}));
  84375. //# sourceMappingURL=babylon.lensFlare.js.map
  84376. var BABYLON;
  84377. (function (BABYLON) {
  84378. // Adds the parser to the scene parsers.
  84379. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84380. // Lens flares
  84381. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84382. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84383. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84384. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84385. container.lensFlareSystems.push(lf);
  84386. }
  84387. }
  84388. });
  84389. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84390. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84391. if (this.lensFlareSystems[index].name === name) {
  84392. return this.lensFlareSystems[index];
  84393. }
  84394. }
  84395. return null;
  84396. };
  84397. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84398. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84399. if (this.lensFlareSystems[index].id === id) {
  84400. return this.lensFlareSystems[index];
  84401. }
  84402. }
  84403. return null;
  84404. };
  84405. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84406. var index = this.lensFlareSystems.indexOf(toRemove);
  84407. if (index !== -1) {
  84408. this.lensFlareSystems.splice(index, 1);
  84409. }
  84410. return index;
  84411. };
  84412. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84413. this.lensFlareSystems.push(newLensFlareSystem);
  84414. };
  84415. /**
  84416. * Defines the lens flare scene component responsible to manage any lens flares
  84417. * in a given scene.
  84418. */
  84419. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84420. /**
  84421. * Creates a new instance of the component for the given scene
  84422. * @param scene Defines the scene to register the component in
  84423. */
  84424. function LensFlareSystemSceneComponent(scene) {
  84425. /**
  84426. * The component name helpfull to identify the component in the list of scene components.
  84427. */
  84428. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84429. this.scene = scene;
  84430. scene.lensFlareSystems = new Array();
  84431. }
  84432. /**
  84433. * Registers the component in a given scene
  84434. */
  84435. LensFlareSystemSceneComponent.prototype.register = function () {
  84436. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84437. };
  84438. /**
  84439. * Rebuilds the elements related to this component in case of
  84440. * context lost for instance.
  84441. */
  84442. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84443. // Nothing to do for lens flare
  84444. };
  84445. /**
  84446. * Adds all the element from the container to the scene
  84447. * @param container the container holding the elements
  84448. */
  84449. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84450. var _this = this;
  84451. if (!container.lensFlareSystems) {
  84452. return;
  84453. }
  84454. container.lensFlareSystems.forEach(function (o) {
  84455. _this.scene.addLensFlareSystem(o);
  84456. });
  84457. };
  84458. /**
  84459. * Removes all the elements in the container from the scene
  84460. * @param container contains the elements to remove
  84461. */
  84462. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84463. var _this = this;
  84464. if (!container.lensFlareSystems) {
  84465. return;
  84466. }
  84467. container.lensFlareSystems.forEach(function (o) {
  84468. _this.scene.removeLensFlareSystem(o);
  84469. });
  84470. };
  84471. /**
  84472. * Serializes the component data to the specified json object
  84473. * @param serializationObject The object to serialize to
  84474. */
  84475. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84476. // Lens flares
  84477. serializationObject.lensFlareSystems = [];
  84478. var lensFlareSystems = this.scene.lensFlareSystems;
  84479. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84480. var lensFlareSystem = lensFlareSystems_1[_i];
  84481. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84482. }
  84483. };
  84484. /**
  84485. * Disposes the component and the associated ressources.
  84486. */
  84487. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84488. var lensFlareSystems = this.scene.lensFlareSystems;
  84489. while (lensFlareSystems.length) {
  84490. lensFlareSystems[0].dispose();
  84491. }
  84492. };
  84493. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84494. // Lens flares
  84495. if (this.scene.lensFlaresEnabled) {
  84496. var lensFlareSystems = this.scene.lensFlareSystems;
  84497. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84498. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84499. var lensFlareSystem = lensFlareSystems_2[_i];
  84500. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84501. lensFlareSystem.render();
  84502. }
  84503. }
  84504. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84505. }
  84506. };
  84507. return LensFlareSystemSceneComponent;
  84508. }());
  84509. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84510. })(BABYLON || (BABYLON = {}));
  84511. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84512. var BABYLON;
  84513. (function (BABYLON) {
  84514. var LensFlareSystem = /** @class */ (function () {
  84515. function LensFlareSystem(name, emitter, scene) {
  84516. this.name = name;
  84517. this.lensFlares = new Array();
  84518. this.borderLimit = 300;
  84519. this.viewportBorder = 0;
  84520. this.layerMask = 0x0FFFFFFF;
  84521. this._vertexBuffers = {};
  84522. this._isEnabled = true;
  84523. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84524. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84525. if (!component) {
  84526. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84527. scene._addComponent(component);
  84528. }
  84529. this._emitter = emitter;
  84530. this.id = name;
  84531. scene.lensFlareSystems.push(this);
  84532. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84533. var engine = scene.getEngine();
  84534. // VBO
  84535. var vertices = [];
  84536. vertices.push(1, 1);
  84537. vertices.push(-1, 1);
  84538. vertices.push(-1, -1);
  84539. vertices.push(1, -1);
  84540. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84541. // Indices
  84542. var indices = [];
  84543. indices.push(0);
  84544. indices.push(1);
  84545. indices.push(2);
  84546. indices.push(0);
  84547. indices.push(2);
  84548. indices.push(3);
  84549. this._indexBuffer = engine.createIndexBuffer(indices);
  84550. // Effects
  84551. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84552. }
  84553. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84554. get: function () {
  84555. return this._isEnabled;
  84556. },
  84557. set: function (value) {
  84558. this._isEnabled = value;
  84559. },
  84560. enumerable: true,
  84561. configurable: true
  84562. });
  84563. LensFlareSystem.prototype.getScene = function () {
  84564. return this._scene;
  84565. };
  84566. LensFlareSystem.prototype.getEmitter = function () {
  84567. return this._emitter;
  84568. };
  84569. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84570. this._emitter = newEmitter;
  84571. };
  84572. LensFlareSystem.prototype.getEmitterPosition = function () {
  84573. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84574. };
  84575. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84576. var position = this.getEmitterPosition();
  84577. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84578. this._positionX = position.x;
  84579. this._positionY = position.y;
  84580. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84581. if (this.viewportBorder > 0) {
  84582. globalViewport.x -= this.viewportBorder;
  84583. globalViewport.y -= this.viewportBorder;
  84584. globalViewport.width += this.viewportBorder * 2;
  84585. globalViewport.height += this.viewportBorder * 2;
  84586. position.x += this.viewportBorder;
  84587. position.y += this.viewportBorder;
  84588. this._positionX += this.viewportBorder;
  84589. this._positionY += this.viewportBorder;
  84590. }
  84591. if (position.z > 0) {
  84592. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84593. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84594. return true;
  84595. }
  84596. return true;
  84597. }
  84598. return false;
  84599. };
  84600. LensFlareSystem.prototype._isVisible = function () {
  84601. if (!this._isEnabled || !this._scene.activeCamera) {
  84602. return false;
  84603. }
  84604. var emitterPosition = this.getEmitterPosition();
  84605. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84606. var distance = direction.length();
  84607. direction.normalize();
  84608. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84609. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84610. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84611. };
  84612. LensFlareSystem.prototype.render = function () {
  84613. if (!this._effect.isReady() || !this._scene.activeCamera)
  84614. return false;
  84615. var engine = this._scene.getEngine();
  84616. var viewport = this._scene.activeCamera.viewport;
  84617. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84618. // Position
  84619. if (!this.computeEffectivePosition(globalViewport)) {
  84620. return false;
  84621. }
  84622. // Visibility
  84623. if (!this._isVisible()) {
  84624. return false;
  84625. }
  84626. // Intensity
  84627. var awayX;
  84628. var awayY;
  84629. if (this._positionX < this.borderLimit + globalViewport.x) {
  84630. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84631. }
  84632. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84633. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84634. }
  84635. else {
  84636. awayX = 0;
  84637. }
  84638. if (this._positionY < this.borderLimit + globalViewport.y) {
  84639. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84640. }
  84641. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84642. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84643. }
  84644. else {
  84645. awayY = 0;
  84646. }
  84647. var away = (awayX > awayY) ? awayX : awayY;
  84648. away -= this.viewportBorder;
  84649. if (away > this.borderLimit) {
  84650. away = this.borderLimit;
  84651. }
  84652. var intensity = 1.0 - (away / this.borderLimit);
  84653. if (intensity < 0) {
  84654. return false;
  84655. }
  84656. if (intensity > 1.0) {
  84657. intensity = 1.0;
  84658. }
  84659. if (this.viewportBorder > 0) {
  84660. globalViewport.x += this.viewportBorder;
  84661. globalViewport.y += this.viewportBorder;
  84662. globalViewport.width -= this.viewportBorder * 2;
  84663. globalViewport.height -= this.viewportBorder * 2;
  84664. this._positionX -= this.viewportBorder;
  84665. this._positionY -= this.viewportBorder;
  84666. }
  84667. // Position
  84668. var centerX = globalViewport.x + globalViewport.width / 2;
  84669. var centerY = globalViewport.y + globalViewport.height / 2;
  84670. var distX = centerX - this._positionX;
  84671. var distY = centerY - this._positionY;
  84672. // Effects
  84673. engine.enableEffect(this._effect);
  84674. engine.setState(false);
  84675. engine.setDepthBuffer(false);
  84676. // VBOs
  84677. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84678. // Flares
  84679. for (var index = 0; index < this.lensFlares.length; index++) {
  84680. var flare = this.lensFlares[index];
  84681. engine.setAlphaMode(flare.alphaMode);
  84682. var x = centerX - (distX * flare.position);
  84683. var y = centerY - (distY * flare.position);
  84684. var cw = flare.size;
  84685. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84686. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84687. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84688. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84689. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84690. // Texture
  84691. this._effect.setTexture("textureSampler", flare.texture);
  84692. // Color
  84693. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84694. // Draw order
  84695. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84696. }
  84697. engine.setDepthBuffer(true);
  84698. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84699. return true;
  84700. };
  84701. LensFlareSystem.prototype.dispose = function () {
  84702. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84703. if (vertexBuffer) {
  84704. vertexBuffer.dispose();
  84705. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84706. }
  84707. if (this._indexBuffer) {
  84708. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84709. this._indexBuffer = null;
  84710. }
  84711. while (this.lensFlares.length) {
  84712. this.lensFlares[0].dispose();
  84713. }
  84714. // Remove from scene
  84715. var index = this._scene.lensFlareSystems.indexOf(this);
  84716. this._scene.lensFlareSystems.splice(index, 1);
  84717. };
  84718. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84719. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84720. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84721. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84722. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84723. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84724. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84725. var parsedFlare = parsedLensFlareSystem.flares[index];
  84726. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84727. }
  84728. return lensFlareSystem;
  84729. };
  84730. LensFlareSystem.prototype.serialize = function () {
  84731. var serializationObject = {};
  84732. serializationObject.id = this.id;
  84733. serializationObject.name = this.name;
  84734. serializationObject.emitterId = this.getEmitter().id;
  84735. serializationObject.borderLimit = this.borderLimit;
  84736. serializationObject.flares = [];
  84737. for (var index = 0; index < this.lensFlares.length; index++) {
  84738. var flare = this.lensFlares[index];
  84739. serializationObject.flares.push({
  84740. size: flare.size,
  84741. position: flare.position,
  84742. color: flare.color.asArray(),
  84743. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84744. });
  84745. }
  84746. return serializationObject;
  84747. };
  84748. return LensFlareSystem;
  84749. }());
  84750. BABYLON.LensFlareSystem = LensFlareSystem;
  84751. })(BABYLON || (BABYLON = {}));
  84752. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84753. var BABYLON;
  84754. (function (BABYLON) {
  84755. /**
  84756. * This is a holder class for the physics joint created by the physics plugin.
  84757. * It holds a set of functions to control the underlying joint.
  84758. */
  84759. var PhysicsJoint = /** @class */ (function () {
  84760. function PhysicsJoint(type, jointData) {
  84761. this.type = type;
  84762. this.jointData = jointData;
  84763. jointData.nativeParams = jointData.nativeParams || {};
  84764. }
  84765. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84766. get: function () {
  84767. return this._physicsJoint;
  84768. },
  84769. set: function (newJoint) {
  84770. if (this._physicsJoint) {
  84771. //remove from the wolrd
  84772. }
  84773. this._physicsJoint = newJoint;
  84774. },
  84775. enumerable: true,
  84776. configurable: true
  84777. });
  84778. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84779. set: function (physicsPlugin) {
  84780. this._physicsPlugin = physicsPlugin;
  84781. },
  84782. enumerable: true,
  84783. configurable: true
  84784. });
  84785. /**
  84786. * Execute a function that is physics-plugin specific.
  84787. * @param {Function} func the function that will be executed.
  84788. * It accepts two parameters: the physics world and the physics joint.
  84789. */
  84790. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84791. func(this._physicsPlugin.world, this._physicsJoint);
  84792. };
  84793. //TODO check if the native joints are the same
  84794. //Joint Types
  84795. PhysicsJoint.DistanceJoint = 0;
  84796. PhysicsJoint.HingeJoint = 1;
  84797. PhysicsJoint.BallAndSocketJoint = 2;
  84798. PhysicsJoint.WheelJoint = 3;
  84799. PhysicsJoint.SliderJoint = 4;
  84800. //OIMO
  84801. PhysicsJoint.PrismaticJoint = 5;
  84802. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84803. PhysicsJoint.UniversalJoint = 6;
  84804. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84805. //Cannon
  84806. //Similar to a Ball-Joint. Different in params
  84807. PhysicsJoint.PointToPointJoint = 8;
  84808. //Cannon only at the moment
  84809. PhysicsJoint.SpringJoint = 9;
  84810. PhysicsJoint.LockJoint = 10;
  84811. return PhysicsJoint;
  84812. }());
  84813. BABYLON.PhysicsJoint = PhysicsJoint;
  84814. /**
  84815. * A class representing a physics distance joint.
  84816. */
  84817. var DistanceJoint = /** @class */ (function (_super) {
  84818. __extends(DistanceJoint, _super);
  84819. function DistanceJoint(jointData) {
  84820. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84821. }
  84822. /**
  84823. * Update the predefined distance.
  84824. */
  84825. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84826. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84827. };
  84828. return DistanceJoint;
  84829. }(PhysicsJoint));
  84830. BABYLON.DistanceJoint = DistanceJoint;
  84831. var MotorEnabledJoint = /** @class */ (function (_super) {
  84832. __extends(MotorEnabledJoint, _super);
  84833. function MotorEnabledJoint(type, jointData) {
  84834. return _super.call(this, type, jointData) || this;
  84835. }
  84836. /**
  84837. * Set the motor values.
  84838. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84839. * @param {number} force the force to apply
  84840. * @param {number} maxForce max force for this motor.
  84841. */
  84842. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84843. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84844. };
  84845. /**
  84846. * Set the motor's limits.
  84847. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84848. */
  84849. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84850. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84851. };
  84852. return MotorEnabledJoint;
  84853. }(PhysicsJoint));
  84854. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84855. /**
  84856. * This class represents a single hinge physics joint
  84857. */
  84858. var HingeJoint = /** @class */ (function (_super) {
  84859. __extends(HingeJoint, _super);
  84860. function HingeJoint(jointData) {
  84861. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84862. }
  84863. /**
  84864. * Set the motor values.
  84865. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84866. * @param {number} force the force to apply
  84867. * @param {number} maxForce max force for this motor.
  84868. */
  84869. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84870. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84871. };
  84872. /**
  84873. * Set the motor's limits.
  84874. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84875. */
  84876. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84877. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84878. };
  84879. return HingeJoint;
  84880. }(MotorEnabledJoint));
  84881. BABYLON.HingeJoint = HingeJoint;
  84882. /**
  84883. * This class represents a dual hinge physics joint (same as wheel joint)
  84884. */
  84885. var Hinge2Joint = /** @class */ (function (_super) {
  84886. __extends(Hinge2Joint, _super);
  84887. function Hinge2Joint(jointData) {
  84888. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84889. }
  84890. /**
  84891. * Set the motor values.
  84892. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84893. * @param {number} force the force to apply
  84894. * @param {number} maxForce max force for this motor.
  84895. * @param {motorIndex} the motor's index, 0 or 1.
  84896. */
  84897. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84898. if (motorIndex === void 0) { motorIndex = 0; }
  84899. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84900. };
  84901. /**
  84902. * Set the motor limits.
  84903. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84904. * @param {number} upperLimit the upper limit
  84905. * @param {number} lowerLimit lower limit
  84906. * @param {motorIndex} the motor's index, 0 or 1.
  84907. */
  84908. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84909. if (motorIndex === void 0) { motorIndex = 0; }
  84910. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84911. };
  84912. return Hinge2Joint;
  84913. }(MotorEnabledJoint));
  84914. BABYLON.Hinge2Joint = Hinge2Joint;
  84915. })(BABYLON || (BABYLON = {}));
  84916. //# sourceMappingURL=babylon.physicsJoint.js.map
  84917. var BABYLON;
  84918. (function (BABYLON) {
  84919. var PhysicsImpostor = /** @class */ (function () {
  84920. function PhysicsImpostor(object, type, _options, _scene) {
  84921. if (_options === void 0) { _options = { mass: 0 }; }
  84922. var _this = this;
  84923. this.object = object;
  84924. this.type = type;
  84925. this._options = _options;
  84926. this._scene = _scene;
  84927. this._bodyUpdateRequired = false;
  84928. this._onBeforePhysicsStepCallbacks = new Array();
  84929. this._onAfterPhysicsStepCallbacks = new Array();
  84930. this._onPhysicsCollideCallbacks = [];
  84931. this._deltaPosition = BABYLON.Vector3.Zero();
  84932. this._isDisposed = false;
  84933. //temp variables for parent rotation calculations
  84934. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84935. this._tmpQuat = new BABYLON.Quaternion();
  84936. this._tmpQuat2 = new BABYLON.Quaternion();
  84937. /**
  84938. * this function is executed by the physics engine.
  84939. */
  84940. this.beforeStep = function () {
  84941. if (!_this._physicsEngine) {
  84942. return;
  84943. }
  84944. _this.object.translate(_this._deltaPosition, -1);
  84945. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84946. _this.object.computeWorldMatrix(false);
  84947. if (_this.object.parent && _this.object.rotationQuaternion) {
  84948. _this.getParentsRotation();
  84949. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84950. }
  84951. else {
  84952. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84953. }
  84954. if (!_this._options.disableBidirectionalTransformation) {
  84955. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84956. }
  84957. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84958. func(_this);
  84959. });
  84960. };
  84961. /**
  84962. * this function is executed by the physics engine.
  84963. */
  84964. this.afterStep = function () {
  84965. if (!_this._physicsEngine) {
  84966. return;
  84967. }
  84968. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84969. func(_this);
  84970. });
  84971. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84972. // object has now its world rotation. needs to be converted to local.
  84973. if (_this.object.parent && _this.object.rotationQuaternion) {
  84974. _this.getParentsRotation();
  84975. _this._tmpQuat.conjugateInPlace();
  84976. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84977. }
  84978. // take the position set and make it the absolute position of this object.
  84979. _this.object.setAbsolutePosition(_this.object.position);
  84980. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84981. _this.object.translate(_this._deltaPosition, 1);
  84982. };
  84983. /**
  84984. * Legacy collision detection event support
  84985. */
  84986. this.onCollideEvent = null;
  84987. //event and body object due to cannon's event-based architecture.
  84988. this.onCollide = function (e) {
  84989. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84990. return;
  84991. }
  84992. if (!_this._physicsEngine) {
  84993. return;
  84994. }
  84995. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84996. if (otherImpostor) {
  84997. // Legacy collision detection event support
  84998. if (_this.onCollideEvent) {
  84999. _this.onCollideEvent(_this, otherImpostor);
  85000. }
  85001. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85002. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85003. }).forEach(function (obj) {
  85004. obj.callback(_this, otherImpostor);
  85005. });
  85006. }
  85007. };
  85008. //sanity check!
  85009. if (!this.object) {
  85010. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85011. return;
  85012. }
  85013. //legacy support for old syntax.
  85014. if (!this._scene && object.getScene) {
  85015. this._scene = object.getScene();
  85016. }
  85017. if (!this._scene) {
  85018. return;
  85019. }
  85020. this._physicsEngine = this._scene.getPhysicsEngine();
  85021. if (!this._physicsEngine) {
  85022. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85023. }
  85024. else {
  85025. //set the object's quaternion, if not set
  85026. if (!this.object.rotationQuaternion) {
  85027. if (this.object.rotation) {
  85028. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85029. }
  85030. else {
  85031. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85032. }
  85033. }
  85034. //default options params
  85035. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85036. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85037. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85038. this._joints = [];
  85039. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85040. if (!this.object.parent || this._options.ignoreParent) {
  85041. this._init();
  85042. }
  85043. else if (this.object.parent.physicsImpostor) {
  85044. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85045. }
  85046. }
  85047. }
  85048. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85049. get: function () {
  85050. return this._isDisposed;
  85051. },
  85052. enumerable: true,
  85053. configurable: true
  85054. });
  85055. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85056. get: function () {
  85057. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85058. },
  85059. set: function (value) {
  85060. this.setMass(value);
  85061. },
  85062. enumerable: true,
  85063. configurable: true
  85064. });
  85065. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85066. get: function () {
  85067. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85068. },
  85069. set: function (value) {
  85070. if (!this._physicsEngine) {
  85071. return;
  85072. }
  85073. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85074. },
  85075. enumerable: true,
  85076. configurable: true
  85077. });
  85078. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85079. get: function () {
  85080. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85081. },
  85082. set: function (value) {
  85083. if (!this._physicsEngine) {
  85084. return;
  85085. }
  85086. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85087. },
  85088. enumerable: true,
  85089. configurable: true
  85090. });
  85091. /**
  85092. * This function will completly initialize this impostor.
  85093. * It will create a new body - but only if this mesh has no parent.
  85094. * If it has, this impostor will not be used other than to define the impostor
  85095. * of the child mesh.
  85096. */
  85097. PhysicsImpostor.prototype._init = function () {
  85098. if (!this._physicsEngine) {
  85099. return;
  85100. }
  85101. this._physicsEngine.removeImpostor(this);
  85102. this.physicsBody = null;
  85103. this._parent = this._parent || this._getPhysicsParent();
  85104. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85105. this._physicsEngine.addImpostor(this);
  85106. }
  85107. };
  85108. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85109. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85110. var parentMesh = this.object.parent;
  85111. return parentMesh.physicsImpostor;
  85112. }
  85113. return null;
  85114. };
  85115. /**
  85116. * Should a new body be generated.
  85117. */
  85118. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85119. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85120. };
  85121. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85122. this.forceUpdate();
  85123. };
  85124. /**
  85125. * Force a regeneration of this or the parent's impostor's body.
  85126. * Use under cautious - This will remove all joints already implemented.
  85127. */
  85128. PhysicsImpostor.prototype.forceUpdate = function () {
  85129. this._init();
  85130. if (this.parent && !this._options.ignoreParent) {
  85131. this.parent.forceUpdate();
  85132. }
  85133. };
  85134. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85135. /*public get mesh(): AbstractMesh {
  85136. return this._mesh;
  85137. }*/
  85138. /**
  85139. * Gets the body that holds this impostor. Either its own, or its parent.
  85140. */
  85141. get: function () {
  85142. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85143. },
  85144. /**
  85145. * Set the physics body. Used mainly by the physics engine/plugin
  85146. */
  85147. set: function (physicsBody) {
  85148. if (this._physicsBody && this._physicsEngine) {
  85149. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85150. }
  85151. this._physicsBody = physicsBody;
  85152. this.resetUpdateFlags();
  85153. },
  85154. enumerable: true,
  85155. configurable: true
  85156. });
  85157. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85158. get: function () {
  85159. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85160. },
  85161. set: function (value) {
  85162. this._parent = value;
  85163. },
  85164. enumerable: true,
  85165. configurable: true
  85166. });
  85167. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85168. this._bodyUpdateRequired = false;
  85169. };
  85170. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85171. if (this.object.getBoundingInfo) {
  85172. var q = this.object.rotationQuaternion;
  85173. //reset rotation
  85174. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85175. //calculate the world matrix with no rotation
  85176. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85177. var boundingInfo = this.object.getBoundingInfo();
  85178. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85179. //bring back the rotation
  85180. this.object.rotationQuaternion = q;
  85181. //calculate the world matrix with the new rotation
  85182. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85183. return size;
  85184. }
  85185. else {
  85186. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85187. }
  85188. };
  85189. PhysicsImpostor.prototype.getObjectCenter = function () {
  85190. if (this.object.getBoundingInfo) {
  85191. var boundingInfo = this.object.getBoundingInfo();
  85192. return boundingInfo.boundingBox.centerWorld;
  85193. }
  85194. else {
  85195. return this.object.position;
  85196. }
  85197. };
  85198. /**
  85199. * Get a specific parametes from the options parameter.
  85200. */
  85201. PhysicsImpostor.prototype.getParam = function (paramName) {
  85202. return this._options[paramName];
  85203. };
  85204. /**
  85205. * Sets a specific parameter in the options given to the physics plugin
  85206. */
  85207. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85208. this._options[paramName] = value;
  85209. this._bodyUpdateRequired = true;
  85210. };
  85211. /**
  85212. * Specifically change the body's mass option. Won't recreate the physics body object
  85213. */
  85214. PhysicsImpostor.prototype.setMass = function (mass) {
  85215. if (this.getParam("mass") !== mass) {
  85216. this.setParam("mass", mass);
  85217. }
  85218. if (this._physicsEngine) {
  85219. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85220. }
  85221. };
  85222. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85223. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85224. };
  85225. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85226. if (this._physicsEngine) {
  85227. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85228. }
  85229. };
  85230. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85231. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85232. };
  85233. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85234. if (this._physicsEngine) {
  85235. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85236. }
  85237. };
  85238. /**
  85239. * Execute a function with the physics plugin native code.
  85240. * Provide a function the will have two variables - the world object and the physics body object.
  85241. */
  85242. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85243. if (this._physicsEngine) {
  85244. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85245. }
  85246. };
  85247. /**
  85248. * Register a function that will be executed before the physics world is stepping forward.
  85249. */
  85250. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85251. this._onBeforePhysicsStepCallbacks.push(func);
  85252. };
  85253. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85254. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85255. if (index > -1) {
  85256. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85257. }
  85258. else {
  85259. BABYLON.Tools.Warn("Function to remove was not found");
  85260. }
  85261. };
  85262. /**
  85263. * Register a function that will be executed after the physics step
  85264. */
  85265. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85266. this._onAfterPhysicsStepCallbacks.push(func);
  85267. };
  85268. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85269. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85270. if (index > -1) {
  85271. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85272. }
  85273. else {
  85274. BABYLON.Tools.Warn("Function to remove was not found");
  85275. }
  85276. };
  85277. /**
  85278. * register a function that will be executed when this impostor collides against a different body.
  85279. */
  85280. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85281. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85282. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85283. };
  85284. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85285. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85286. var index = -1;
  85287. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85288. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85289. // chcek the arrays match
  85290. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85291. return collidedAgainstList.indexOf(impostor) > -1;
  85292. });
  85293. if (sameList) {
  85294. index = idx;
  85295. }
  85296. return sameList;
  85297. }
  85298. return false;
  85299. });
  85300. if (found) {
  85301. this._onPhysicsCollideCallbacks.splice(index, 1);
  85302. }
  85303. else {
  85304. BABYLON.Tools.Warn("Function to remove was not found");
  85305. }
  85306. };
  85307. PhysicsImpostor.prototype.getParentsRotation = function () {
  85308. var parent = this.object.parent;
  85309. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85310. while (parent) {
  85311. if (parent.rotationQuaternion) {
  85312. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85313. }
  85314. else {
  85315. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85316. }
  85317. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85318. parent = parent.parent;
  85319. }
  85320. return this._tmpQuat;
  85321. };
  85322. /**
  85323. * Apply a force
  85324. */
  85325. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85326. if (this._physicsEngine) {
  85327. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85328. }
  85329. return this;
  85330. };
  85331. /**
  85332. * Apply an impulse
  85333. */
  85334. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85335. if (this._physicsEngine) {
  85336. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85337. }
  85338. return this;
  85339. };
  85340. /**
  85341. * A help function to create a joint.
  85342. */
  85343. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85344. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85345. this.addJoint(otherImpostor, joint);
  85346. return this;
  85347. };
  85348. /**
  85349. * Add a joint to this impostor with a different impostor.
  85350. */
  85351. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85352. this._joints.push({
  85353. otherImpostor: otherImpostor,
  85354. joint: joint
  85355. });
  85356. if (this._physicsEngine) {
  85357. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85358. }
  85359. return this;
  85360. };
  85361. /**
  85362. * Will keep this body still, in a sleep mode.
  85363. */
  85364. PhysicsImpostor.prototype.sleep = function () {
  85365. if (this._physicsEngine) {
  85366. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85367. }
  85368. return this;
  85369. };
  85370. /**
  85371. * Wake the body up.
  85372. */
  85373. PhysicsImpostor.prototype.wakeUp = function () {
  85374. if (this._physicsEngine) {
  85375. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85376. }
  85377. return this;
  85378. };
  85379. PhysicsImpostor.prototype.clone = function (newObject) {
  85380. if (!newObject)
  85381. return null;
  85382. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85383. };
  85384. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85385. var _this = this;
  85386. //no dispose if no physics engine is available.
  85387. if (!this._physicsEngine) {
  85388. return;
  85389. }
  85390. this._joints.forEach(function (j) {
  85391. if (_this._physicsEngine) {
  85392. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85393. }
  85394. });
  85395. //dispose the physics body
  85396. this._physicsEngine.removeImpostor(this);
  85397. if (this.parent) {
  85398. this.parent.forceUpdate();
  85399. }
  85400. else {
  85401. /*this._object.getChildMeshes().forEach(function(mesh) {
  85402. if (mesh.physicsImpostor) {
  85403. if (disposeChildren) {
  85404. mesh.physicsImpostor.dispose();
  85405. mesh.physicsImpostor = null;
  85406. }
  85407. }
  85408. })*/
  85409. }
  85410. this._isDisposed = true;
  85411. };
  85412. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85413. this._deltaPosition.copyFrom(position);
  85414. };
  85415. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85416. if (!this._deltaRotation) {
  85417. this._deltaRotation = new BABYLON.Quaternion();
  85418. }
  85419. this._deltaRotation.copyFrom(rotation);
  85420. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85421. };
  85422. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85423. if (this._physicsEngine) {
  85424. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85425. }
  85426. return this;
  85427. };
  85428. PhysicsImpostor.prototype.getRadius = function () {
  85429. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85430. };
  85431. /**
  85432. * Sync a bone with this impostor
  85433. * @param bone The bone to sync to the impostor.
  85434. * @param boneMesh The mesh that the bone is influencing.
  85435. * @param jointPivot The pivot of the joint / bone in local space.
  85436. * @param distToJoint Optional distance from the impostor to the joint.
  85437. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85438. */
  85439. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85440. var tempVec = PhysicsImpostor._tmpVecs[0];
  85441. var mesh = this.object;
  85442. if (mesh.rotationQuaternion) {
  85443. if (adjustRotation) {
  85444. var tempQuat = PhysicsImpostor._tmpQuat;
  85445. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85446. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85447. }
  85448. else {
  85449. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85450. }
  85451. }
  85452. tempVec.x = 0;
  85453. tempVec.y = 0;
  85454. tempVec.z = 0;
  85455. if (jointPivot) {
  85456. tempVec.x = jointPivot.x;
  85457. tempVec.y = jointPivot.y;
  85458. tempVec.z = jointPivot.z;
  85459. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85460. if (distToJoint === undefined || distToJoint === null) {
  85461. distToJoint = jointPivot.length();
  85462. }
  85463. tempVec.x *= distToJoint;
  85464. tempVec.y *= distToJoint;
  85465. tempVec.z *= distToJoint;
  85466. }
  85467. if (bone.getParent()) {
  85468. tempVec.addInPlace(mesh.getAbsolutePosition());
  85469. bone.setAbsolutePosition(tempVec, boneMesh);
  85470. }
  85471. else {
  85472. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85473. boneMesh.position.x -= tempVec.x;
  85474. boneMesh.position.y -= tempVec.y;
  85475. boneMesh.position.z -= tempVec.z;
  85476. }
  85477. };
  85478. /**
  85479. * Sync impostor to a bone
  85480. * @param bone The bone that the impostor will be synced to.
  85481. * @param boneMesh The mesh that the bone is influencing.
  85482. * @param jointPivot The pivot of the joint / bone in local space.
  85483. * @param distToJoint Optional distance from the impostor to the joint.
  85484. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85485. * @param boneAxis Optional vector3 axis the bone is aligned with
  85486. */
  85487. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85488. var mesh = this.object;
  85489. if (mesh.rotationQuaternion) {
  85490. if (adjustRotation) {
  85491. var tempQuat = PhysicsImpostor._tmpQuat;
  85492. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85493. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85494. }
  85495. else {
  85496. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85497. }
  85498. }
  85499. var pos = PhysicsImpostor._tmpVecs[0];
  85500. var boneDir = PhysicsImpostor._tmpVecs[1];
  85501. if (!boneAxis) {
  85502. boneAxis = PhysicsImpostor._tmpVecs[2];
  85503. boneAxis.x = 0;
  85504. boneAxis.y = 1;
  85505. boneAxis.z = 0;
  85506. }
  85507. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85508. bone.getAbsolutePositionToRef(boneMesh, pos);
  85509. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85510. distToJoint = jointPivot.length();
  85511. }
  85512. if (distToJoint !== undefined && distToJoint !== null) {
  85513. pos.x += boneDir.x * distToJoint;
  85514. pos.y += boneDir.y * distToJoint;
  85515. pos.z += boneDir.z * distToJoint;
  85516. }
  85517. mesh.setAbsolutePosition(pos);
  85518. };
  85519. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85520. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85521. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85522. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85523. //Impostor types
  85524. PhysicsImpostor.NoImpostor = 0;
  85525. PhysicsImpostor.SphereImpostor = 1;
  85526. PhysicsImpostor.BoxImpostor = 2;
  85527. PhysicsImpostor.PlaneImpostor = 3;
  85528. PhysicsImpostor.MeshImpostor = 4;
  85529. PhysicsImpostor.CylinderImpostor = 7;
  85530. PhysicsImpostor.ParticleImpostor = 8;
  85531. PhysicsImpostor.HeightmapImpostor = 9;
  85532. return PhysicsImpostor;
  85533. }());
  85534. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85535. })(BABYLON || (BABYLON = {}));
  85536. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85537. var BABYLON;
  85538. (function (BABYLON) {
  85539. var PhysicsEngine = /** @class */ (function () {
  85540. function PhysicsEngine(gravity, _physicsPlugin) {
  85541. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85542. this._physicsPlugin = _physicsPlugin;
  85543. //new methods and parameters
  85544. this._impostors = [];
  85545. this._joints = [];
  85546. if (!this._physicsPlugin.isSupported()) {
  85547. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85548. + "Please make sure it is included.");
  85549. }
  85550. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85551. this.setGravity(gravity);
  85552. this.setTimeStep();
  85553. }
  85554. PhysicsEngine.prototype.setGravity = function (gravity) {
  85555. this.gravity = gravity;
  85556. this._physicsPlugin.setGravity(this.gravity);
  85557. };
  85558. /**
  85559. * Set the time step of the physics engine.
  85560. * default is 1/60.
  85561. * To slow it down, enter 1/600 for example.
  85562. * To speed it up, 1/30
  85563. * @param {number} newTimeStep the new timestep to apply to this world.
  85564. */
  85565. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85566. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85567. this._physicsPlugin.setTimeStep(newTimeStep);
  85568. };
  85569. /**
  85570. * Get the time step of the physics engine.
  85571. */
  85572. PhysicsEngine.prototype.getTimeStep = function () {
  85573. return this._physicsPlugin.getTimeStep();
  85574. };
  85575. PhysicsEngine.prototype.dispose = function () {
  85576. this._impostors.forEach(function (impostor) {
  85577. impostor.dispose();
  85578. });
  85579. this._physicsPlugin.dispose();
  85580. };
  85581. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85582. return this._physicsPlugin.name;
  85583. };
  85584. /**
  85585. * Adding a new impostor for the impostor tracking.
  85586. * This will be done by the impostor itself.
  85587. * @param {PhysicsImpostor} impostor the impostor to add
  85588. */
  85589. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85590. impostor.uniqueId = this._impostors.push(impostor);
  85591. //if no parent, generate the body
  85592. if (!impostor.parent) {
  85593. this._physicsPlugin.generatePhysicsBody(impostor);
  85594. }
  85595. };
  85596. /**
  85597. * Remove an impostor from the engine.
  85598. * This impostor and its mesh will not longer be updated by the physics engine.
  85599. * @param {PhysicsImpostor} impostor the impostor to remove
  85600. */
  85601. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85602. var index = this._impostors.indexOf(impostor);
  85603. if (index > -1) {
  85604. var removed = this._impostors.splice(index, 1);
  85605. //Is it needed?
  85606. if (removed.length) {
  85607. //this will also remove it from the world.
  85608. removed[0].physicsBody = null;
  85609. }
  85610. }
  85611. };
  85612. /**
  85613. * Add a joint to the physics engine
  85614. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85615. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85616. * @param {PhysicsJoint} the joint that will connect both impostors.
  85617. */
  85618. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85619. var impostorJoint = {
  85620. mainImpostor: mainImpostor,
  85621. connectedImpostor: connectedImpostor,
  85622. joint: joint
  85623. };
  85624. joint.physicsPlugin = this._physicsPlugin;
  85625. this._joints.push(impostorJoint);
  85626. this._physicsPlugin.generateJoint(impostorJoint);
  85627. };
  85628. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85629. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85630. return (impostorJoint.connectedImpostor === connectedImpostor
  85631. && impostorJoint.joint === joint
  85632. && impostorJoint.mainImpostor === mainImpostor);
  85633. });
  85634. if (matchingJoints.length) {
  85635. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85636. //TODO remove it from the list as well
  85637. }
  85638. };
  85639. /**
  85640. * Called by the scene. no need to call it.
  85641. */
  85642. PhysicsEngine.prototype._step = function (delta) {
  85643. var _this = this;
  85644. //check if any mesh has no body / requires an update
  85645. this._impostors.forEach(function (impostor) {
  85646. if (impostor.isBodyInitRequired()) {
  85647. _this._physicsPlugin.generatePhysicsBody(impostor);
  85648. }
  85649. });
  85650. if (delta > 0.1) {
  85651. delta = 0.1;
  85652. }
  85653. else if (delta <= 0) {
  85654. delta = 1.0 / 60.0;
  85655. }
  85656. this._physicsPlugin.executeStep(delta, this._impostors);
  85657. };
  85658. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85659. return this._physicsPlugin;
  85660. };
  85661. PhysicsEngine.prototype.getImpostors = function () {
  85662. return this._impostors;
  85663. };
  85664. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85665. for (var i = 0; i < this._impostors.length; ++i) {
  85666. if (this._impostors[i].object === object) {
  85667. return this._impostors[i];
  85668. }
  85669. }
  85670. return null;
  85671. };
  85672. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85673. for (var i = 0; i < this._impostors.length; ++i) {
  85674. if (this._impostors[i].physicsBody === body) {
  85675. return this._impostors[i];
  85676. }
  85677. }
  85678. return null;
  85679. };
  85680. // Statics
  85681. PhysicsEngine.Epsilon = 0.001;
  85682. return PhysicsEngine;
  85683. }());
  85684. BABYLON.PhysicsEngine = PhysicsEngine;
  85685. })(BABYLON || (BABYLON = {}));
  85686. //# sourceMappingURL=babylon.physicsEngine.js.map
  85687. var BABYLON;
  85688. (function (BABYLON) {
  85689. var PhysicsHelper = /** @class */ (function () {
  85690. function PhysicsHelper(scene) {
  85691. this._scene = scene;
  85692. this._physicsEngine = this._scene.getPhysicsEngine();
  85693. if (!this._physicsEngine) {
  85694. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85695. }
  85696. }
  85697. /**
  85698. * @param {Vector3} origin the origin of the explosion
  85699. * @param {number} radius the explosion radius
  85700. * @param {number} strength the explosion strength
  85701. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85702. */
  85703. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85704. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85705. if (!this._physicsEngine) {
  85706. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85707. return null;
  85708. }
  85709. var impostors = this._physicsEngine.getImpostors();
  85710. if (impostors.length === 0) {
  85711. return null;
  85712. }
  85713. var event = new PhysicsRadialExplosionEvent(this._scene);
  85714. impostors.forEach(function (impostor) {
  85715. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85716. if (!impostorForceAndContactPoint) {
  85717. return;
  85718. }
  85719. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85720. });
  85721. event.dispose(false);
  85722. return event;
  85723. };
  85724. /**
  85725. * @param {Vector3} origin the origin of the explosion
  85726. * @param {number} radius the explosion radius
  85727. * @param {number} strength the explosion strength
  85728. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85729. */
  85730. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85731. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85732. if (!this._physicsEngine) {
  85733. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85734. return null;
  85735. }
  85736. var impostors = this._physicsEngine.getImpostors();
  85737. if (impostors.length === 0) {
  85738. return null;
  85739. }
  85740. var event = new PhysicsRadialExplosionEvent(this._scene);
  85741. impostors.forEach(function (impostor) {
  85742. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85743. if (!impostorForceAndContactPoint) {
  85744. return;
  85745. }
  85746. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85747. });
  85748. event.dispose(false);
  85749. return event;
  85750. };
  85751. /**
  85752. * @param {Vector3} origin the origin of the explosion
  85753. * @param {number} radius the explosion radius
  85754. * @param {number} strength the explosion strength
  85755. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85756. */
  85757. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85758. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85759. if (!this._physicsEngine) {
  85760. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85761. return null;
  85762. }
  85763. var impostors = this._physicsEngine.getImpostors();
  85764. if (impostors.length === 0) {
  85765. return null;
  85766. }
  85767. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85768. event.dispose(false);
  85769. return event;
  85770. };
  85771. /**
  85772. * @param {Vector3} origin the origin of the updraft
  85773. * @param {number} radius the radius of the updraft
  85774. * @param {number} strength the strength of the updraft
  85775. * @param {number} height the height of the updraft
  85776. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85777. */
  85778. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85779. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85780. if (!this._physicsEngine) {
  85781. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85782. return null;
  85783. }
  85784. if (this._physicsEngine.getImpostors().length === 0) {
  85785. return null;
  85786. }
  85787. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85788. event.dispose(false);
  85789. return event;
  85790. };
  85791. /**
  85792. * @param {Vector3} origin the of the vortex
  85793. * @param {number} radius the radius of the vortex
  85794. * @param {number} strength the strength of the vortex
  85795. * @param {number} height the height of the vortex
  85796. */
  85797. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85798. if (!this._physicsEngine) {
  85799. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85800. return null;
  85801. }
  85802. if (this._physicsEngine.getImpostors().length === 0) {
  85803. return null;
  85804. }
  85805. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85806. event.dispose(false);
  85807. return event;
  85808. };
  85809. return PhysicsHelper;
  85810. }());
  85811. BABYLON.PhysicsHelper = PhysicsHelper;
  85812. /***** Radial explosion *****/
  85813. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85814. function PhysicsRadialExplosionEvent(scene) {
  85815. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85816. this._rays = [];
  85817. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85818. this._scene = scene;
  85819. }
  85820. /**
  85821. * Returns the data related to the radial explosion event (sphere & rays).
  85822. * @returns {PhysicsRadialExplosionEventData}
  85823. */
  85824. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85825. this._dataFetched = true;
  85826. return {
  85827. sphere: this._sphere,
  85828. rays: this._rays,
  85829. };
  85830. };
  85831. /**
  85832. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85833. * @param impostor
  85834. * @param {Vector3} origin the origin of the explosion
  85835. * @param {number} radius the explosion radius
  85836. * @param {number} strength the explosion strength
  85837. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85838. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85839. */
  85840. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85841. if (impostor.mass === 0) {
  85842. return null;
  85843. }
  85844. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85845. return null;
  85846. }
  85847. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85848. return null;
  85849. }
  85850. var impostorObjectCenter = impostor.getObjectCenter();
  85851. var direction = impostorObjectCenter.subtract(origin);
  85852. var ray = new BABYLON.Ray(origin, direction, radius);
  85853. this._rays.push(ray);
  85854. var hit = ray.intersectsMesh(impostor.object);
  85855. var contactPoint = hit.pickedPoint;
  85856. if (!contactPoint) {
  85857. return null;
  85858. }
  85859. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85860. if (distanceFromOrigin > radius) {
  85861. return null;
  85862. }
  85863. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85864. ? strength
  85865. : strength * (1 - (distanceFromOrigin / radius));
  85866. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85867. return { force: force, contactPoint: contactPoint };
  85868. };
  85869. /**
  85870. * Disposes the sphere.
  85871. * @param {bolean} force
  85872. */
  85873. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85874. var _this = this;
  85875. if (force === void 0) { force = true; }
  85876. if (force) {
  85877. this._sphere.dispose();
  85878. }
  85879. else {
  85880. setTimeout(function () {
  85881. if (!_this._dataFetched) {
  85882. _this._sphere.dispose();
  85883. }
  85884. }, 0);
  85885. }
  85886. };
  85887. /*** Helpers ***/
  85888. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85889. if (!this._sphere) {
  85890. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85891. this._sphere.isVisible = false;
  85892. }
  85893. };
  85894. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85895. var impostorObject = impostor.object;
  85896. this._prepareSphere();
  85897. this._sphere.position = origin;
  85898. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85899. this._sphere._updateBoundingInfo();
  85900. this._sphere.computeWorldMatrix(true);
  85901. return this._sphere.intersectsMesh(impostorObject, true);
  85902. };
  85903. return PhysicsRadialExplosionEvent;
  85904. }());
  85905. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85906. /***** Gravitational Field *****/
  85907. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85908. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85909. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85910. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85911. this._physicsHelper = physicsHelper;
  85912. this._scene = scene;
  85913. this._origin = origin;
  85914. this._radius = radius;
  85915. this._strength = strength;
  85916. this._falloff = falloff;
  85917. this._tickCallback = this._tick.bind(this);
  85918. }
  85919. /**
  85920. * Returns the data related to the gravitational field event (sphere).
  85921. * @returns {PhysicsGravitationalFieldEventData}
  85922. */
  85923. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85924. this._dataFetched = true;
  85925. return {
  85926. sphere: this._sphere,
  85927. };
  85928. };
  85929. /**
  85930. * Enables the gravitational field.
  85931. */
  85932. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85933. this._tickCallback.call(this);
  85934. this._scene.registerBeforeRender(this._tickCallback);
  85935. };
  85936. /**
  85937. * Disables the gravitational field.
  85938. */
  85939. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85940. this._scene.unregisterBeforeRender(this._tickCallback);
  85941. };
  85942. /**
  85943. * Disposes the sphere.
  85944. * @param {bolean} force
  85945. */
  85946. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85947. var _this = this;
  85948. if (force === void 0) { force = true; }
  85949. if (force) {
  85950. this._sphere.dispose();
  85951. }
  85952. else {
  85953. setTimeout(function () {
  85954. if (!_this._dataFetched) {
  85955. _this._sphere.dispose();
  85956. }
  85957. }, 0);
  85958. }
  85959. };
  85960. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85961. // Since the params won't change, we fetch the event only once
  85962. if (this._sphere) {
  85963. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85964. }
  85965. else {
  85966. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85967. if (radialExplosionEvent) {
  85968. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85969. }
  85970. }
  85971. };
  85972. return PhysicsGravitationalFieldEvent;
  85973. }());
  85974. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85975. /***** Updraft *****/
  85976. var PhysicsUpdraftEvent = /** @class */ (function () {
  85977. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85978. this._scene = _scene;
  85979. this._origin = _origin;
  85980. this._radius = _radius;
  85981. this._strength = _strength;
  85982. this._height = _height;
  85983. this._updraftMode = _updraftMode;
  85984. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85985. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85986. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85987. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85988. this._physicsEngine = this._scene.getPhysicsEngine();
  85989. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85990. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85991. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85992. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85993. }
  85994. this._tickCallback = this._tick.bind(this);
  85995. }
  85996. /**
  85997. * Returns the data related to the updraft event (cylinder).
  85998. * @returns {PhysicsUpdraftEventData}
  85999. */
  86000. PhysicsUpdraftEvent.prototype.getData = function () {
  86001. this._dataFetched = true;
  86002. return {
  86003. cylinder: this._cylinder,
  86004. };
  86005. };
  86006. /**
  86007. * Enables the updraft.
  86008. */
  86009. PhysicsUpdraftEvent.prototype.enable = function () {
  86010. this._tickCallback.call(this);
  86011. this._scene.registerBeforeRender(this._tickCallback);
  86012. };
  86013. /**
  86014. * Disables the cortex.
  86015. */
  86016. PhysicsUpdraftEvent.prototype.disable = function () {
  86017. this._scene.unregisterBeforeRender(this._tickCallback);
  86018. };
  86019. /**
  86020. * Disposes the sphere.
  86021. * @param {bolean} force
  86022. */
  86023. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86024. var _this = this;
  86025. if (force === void 0) { force = true; }
  86026. if (force) {
  86027. this._cylinder.dispose();
  86028. }
  86029. else {
  86030. setTimeout(function () {
  86031. if (!_this._dataFetched) {
  86032. _this._cylinder.dispose();
  86033. }
  86034. }, 0);
  86035. }
  86036. };
  86037. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86038. if (impostor.mass === 0) {
  86039. return null;
  86040. }
  86041. if (!this._intersectsWithCylinder(impostor)) {
  86042. return null;
  86043. }
  86044. var impostorObjectCenter = impostor.getObjectCenter();
  86045. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86046. var direction = this._originDirection;
  86047. }
  86048. else {
  86049. var direction = impostorObjectCenter.subtract(this._originTop);
  86050. }
  86051. var multiplier = this._strength * -1;
  86052. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86053. return { force: force, contactPoint: impostorObjectCenter };
  86054. };
  86055. PhysicsUpdraftEvent.prototype._tick = function () {
  86056. var _this = this;
  86057. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86058. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86059. if (!impostorForceAndContactPoint) {
  86060. return;
  86061. }
  86062. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86063. });
  86064. };
  86065. /*** Helpers ***/
  86066. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86067. if (!this._cylinder) {
  86068. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86069. height: this._height,
  86070. diameter: this._radius * 2,
  86071. }, this._scene);
  86072. this._cylinder.isVisible = false;
  86073. }
  86074. };
  86075. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86076. var impostorObject = impostor.object;
  86077. this._prepareCylinder();
  86078. this._cylinder.position = this._cylinderPosition;
  86079. return this._cylinder.intersectsMesh(impostorObject, true);
  86080. };
  86081. return PhysicsUpdraftEvent;
  86082. }());
  86083. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86084. /***** Vortex *****/
  86085. var PhysicsVortexEvent = /** @class */ (function () {
  86086. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86087. this._scene = _scene;
  86088. this._origin = _origin;
  86089. this._radius = _radius;
  86090. this._strength = _strength;
  86091. this._height = _height;
  86092. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86093. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86094. this._updraftMultiplier = 0.02;
  86095. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86096. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86097. this._physicsEngine = this._scene.getPhysicsEngine();
  86098. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86099. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86100. this._tickCallback = this._tick.bind(this);
  86101. }
  86102. /**
  86103. * Returns the data related to the vortex event (cylinder).
  86104. * @returns {PhysicsVortexEventData}
  86105. */
  86106. PhysicsVortexEvent.prototype.getData = function () {
  86107. this._dataFetched = true;
  86108. return {
  86109. cylinder: this._cylinder,
  86110. };
  86111. };
  86112. /**
  86113. * Enables the vortex.
  86114. */
  86115. PhysicsVortexEvent.prototype.enable = function () {
  86116. this._tickCallback.call(this);
  86117. this._scene.registerBeforeRender(this._tickCallback);
  86118. };
  86119. /**
  86120. * Disables the cortex.
  86121. */
  86122. PhysicsVortexEvent.prototype.disable = function () {
  86123. this._scene.unregisterBeforeRender(this._tickCallback);
  86124. };
  86125. /**
  86126. * Disposes the sphere.
  86127. * @param {bolean} force
  86128. */
  86129. PhysicsVortexEvent.prototype.dispose = function (force) {
  86130. var _this = this;
  86131. if (force === void 0) { force = true; }
  86132. if (force) {
  86133. this._cylinder.dispose();
  86134. }
  86135. else {
  86136. setTimeout(function () {
  86137. if (!_this._dataFetched) {
  86138. _this._cylinder.dispose();
  86139. }
  86140. }, 0);
  86141. }
  86142. };
  86143. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86144. if (impostor.mass === 0) {
  86145. return null;
  86146. }
  86147. if (!this._intersectsWithCylinder(impostor)) {
  86148. return null;
  86149. }
  86150. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86151. return null;
  86152. }
  86153. var impostorObjectCenter = impostor.getObjectCenter();
  86154. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  86155. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86156. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86157. var hit = ray.intersectsMesh(impostor.object);
  86158. var contactPoint = hit.pickedPoint;
  86159. if (!contactPoint) {
  86160. return null;
  86161. }
  86162. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86163. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86164. var directionToOrigin = contactPoint.normalize();
  86165. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86166. directionToOrigin = directionToOrigin.negate();
  86167. }
  86168. // TODO: find a more physically based solution
  86169. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86170. var forceX = directionToOrigin.x * this._strength / 8;
  86171. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86172. var forceZ = directionToOrigin.z * this._strength / 8;
  86173. }
  86174. else {
  86175. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86176. var forceY = this._originTop.y * this._updraftMultiplier;
  86177. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86178. }
  86179. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86180. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86181. return { force: force, contactPoint: impostorObjectCenter };
  86182. };
  86183. PhysicsVortexEvent.prototype._tick = function () {
  86184. var _this = this;
  86185. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86186. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86187. if (!impostorForceAndContactPoint) {
  86188. return;
  86189. }
  86190. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86191. });
  86192. };
  86193. /*** Helpers ***/
  86194. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86195. if (!this._cylinder) {
  86196. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86197. height: this._height,
  86198. diameter: this._radius * 2,
  86199. }, this._scene);
  86200. this._cylinder.isVisible = false;
  86201. }
  86202. };
  86203. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86204. var impostorObject = impostor.object;
  86205. this._prepareCylinder();
  86206. this._cylinder.position = this._cylinderPosition;
  86207. return this._cylinder.intersectsMesh(impostorObject, true);
  86208. };
  86209. return PhysicsVortexEvent;
  86210. }());
  86211. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86212. /***** Enums *****/
  86213. /**
  86214. * The strenght of the force in correspondence to the distance of the affected object
  86215. */
  86216. var PhysicsRadialImpulseFalloff;
  86217. (function (PhysicsRadialImpulseFalloff) {
  86218. /** Defines that impulse is constant in strength across it's whole radius */
  86219. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86220. /** DEfines that impulse gets weaker if it's further from the origin */
  86221. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86222. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86223. /**
  86224. * The strenght of the force in correspondence to the distance of the affected object
  86225. */
  86226. var PhysicsUpdraftMode;
  86227. (function (PhysicsUpdraftMode) {
  86228. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86229. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86230. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86231. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86232. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86233. })(BABYLON || (BABYLON = {}));
  86234. //# sourceMappingURL=babylon.physicsHelper.js.map
  86235. var BABYLON;
  86236. (function (BABYLON) {
  86237. var CannonJSPlugin = /** @class */ (function () {
  86238. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86239. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86240. if (iterations === void 0) { iterations = 10; }
  86241. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86242. this.name = "CannonJSPlugin";
  86243. this._physicsMaterials = new Array();
  86244. this._fixedTimeStep = 1 / 60;
  86245. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86246. this.BJSCANNON = CANNON;
  86247. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86248. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86249. this._tmpPosition = BABYLON.Vector3.Zero();
  86250. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86251. this._tmpUnityRotation = new BABYLON.Quaternion();
  86252. if (!this.isSupported()) {
  86253. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86254. return;
  86255. }
  86256. this._extendNamespace();
  86257. this.world = new this.BJSCANNON.World();
  86258. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86259. this.world.solver.iterations = iterations;
  86260. }
  86261. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86262. this.world.gravity.copy(gravity);
  86263. };
  86264. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86265. this._fixedTimeStep = timeStep;
  86266. };
  86267. CannonJSPlugin.prototype.getTimeStep = function () {
  86268. return this._fixedTimeStep;
  86269. };
  86270. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86271. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86272. };
  86273. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86274. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86275. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86276. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86277. };
  86278. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86279. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86280. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86281. impostor.physicsBody.applyForce(impulse, worldPoint);
  86282. };
  86283. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86284. //parent-child relationship. Does this impostor has a parent impostor?
  86285. if (impostor.parent) {
  86286. if (impostor.physicsBody) {
  86287. this.removePhysicsBody(impostor);
  86288. //TODO is that needed?
  86289. impostor.forceUpdate();
  86290. }
  86291. return;
  86292. }
  86293. //should a new body be created for this impostor?
  86294. if (impostor.isBodyInitRequired()) {
  86295. var shape = this._createShape(impostor);
  86296. //unregister events, if body is being changed
  86297. var oldBody = impostor.physicsBody;
  86298. if (oldBody) {
  86299. this.removePhysicsBody(impostor);
  86300. }
  86301. //create the body and material
  86302. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86303. var bodyCreationObject = {
  86304. mass: impostor.getParam("mass"),
  86305. material: material
  86306. };
  86307. // A simple extend, in case native options were used.
  86308. var nativeOptions = impostor.getParam("nativeOptions");
  86309. for (var key in nativeOptions) {
  86310. if (nativeOptions.hasOwnProperty(key)) {
  86311. bodyCreationObject[key] = nativeOptions[key];
  86312. }
  86313. }
  86314. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86315. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86316. this.world.addEventListener("preStep", impostor.beforeStep);
  86317. this.world.addEventListener("postStep", impostor.afterStep);
  86318. impostor.physicsBody.addShape(shape);
  86319. this.world.add(impostor.physicsBody);
  86320. //try to keep the body moving in the right direction by taking old properties.
  86321. //Should be tested!
  86322. if (oldBody) {
  86323. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86324. impostor.physicsBody[param].copy(oldBody[param]);
  86325. });
  86326. }
  86327. this._processChildMeshes(impostor);
  86328. }
  86329. //now update the body's transformation
  86330. this._updatePhysicsBodyTransformation(impostor);
  86331. };
  86332. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86333. var _this = this;
  86334. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86335. var currentRotation = mainImpostor.object.rotationQuaternion;
  86336. if (meshChildren.length) {
  86337. var processMesh = function (localPosition, mesh) {
  86338. if (!currentRotation || !mesh.rotationQuaternion) {
  86339. return;
  86340. }
  86341. var childImpostor = mesh.getPhysicsImpostor();
  86342. if (childImpostor) {
  86343. var parent = childImpostor.parent;
  86344. if (parent !== mainImpostor) {
  86345. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86346. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86347. if (childImpostor.physicsBody) {
  86348. _this.removePhysicsBody(childImpostor);
  86349. childImpostor.physicsBody = null;
  86350. }
  86351. childImpostor.parent = mainImpostor;
  86352. childImpostor.resetUpdateFlags();
  86353. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  86354. //Add the mass of the children.
  86355. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86356. }
  86357. }
  86358. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86359. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86360. };
  86361. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86362. }
  86363. };
  86364. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86365. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86366. this.world.removeEventListener("preStep", impostor.beforeStep);
  86367. this.world.removeEventListener("postStep", impostor.afterStep);
  86368. this.world.remove(impostor.physicsBody);
  86369. };
  86370. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86371. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86372. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86373. if (!mainBody || !connectedBody) {
  86374. return;
  86375. }
  86376. var constraint;
  86377. var jointData = impostorJoint.joint.jointData;
  86378. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86379. var constraintData = {
  86380. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86381. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86382. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86383. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86384. maxForce: jointData.nativeParams.maxForce,
  86385. collideConnected: !!jointData.collision
  86386. };
  86387. switch (impostorJoint.joint.type) {
  86388. case BABYLON.PhysicsJoint.HingeJoint:
  86389. case BABYLON.PhysicsJoint.Hinge2Joint:
  86390. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86391. break;
  86392. case BABYLON.PhysicsJoint.DistanceJoint:
  86393. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86394. break;
  86395. case BABYLON.PhysicsJoint.SpringJoint:
  86396. var springData = jointData;
  86397. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86398. restLength: springData.length,
  86399. stiffness: springData.stiffness,
  86400. damping: springData.damping,
  86401. localAnchorA: constraintData.pivotA,
  86402. localAnchorB: constraintData.pivotB
  86403. });
  86404. break;
  86405. case BABYLON.PhysicsJoint.LockJoint:
  86406. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86407. break;
  86408. case BABYLON.PhysicsJoint.PointToPointJoint:
  86409. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86410. default:
  86411. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86412. break;
  86413. }
  86414. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86415. constraint.collideConnected = !!jointData.collision;
  86416. impostorJoint.joint.physicsJoint = constraint;
  86417. //don't add spring as constraint, as it is not one.
  86418. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86419. this.world.addConstraint(constraint);
  86420. }
  86421. else {
  86422. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86423. constraint.applyForce();
  86424. });
  86425. }
  86426. };
  86427. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86428. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86429. };
  86430. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86431. var index;
  86432. var mat;
  86433. for (index = 0; index < this._physicsMaterials.length; index++) {
  86434. mat = this._physicsMaterials[index];
  86435. if (mat.friction === friction && mat.restitution === restitution) {
  86436. return mat;
  86437. }
  86438. }
  86439. var currentMat = new this.BJSCANNON.Material(name);
  86440. currentMat.friction = friction;
  86441. currentMat.restitution = restitution;
  86442. this._physicsMaterials.push(currentMat);
  86443. return currentMat;
  86444. };
  86445. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86446. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86447. };
  86448. CannonJSPlugin.prototype._createShape = function (impostor) {
  86449. var object = impostor.object;
  86450. var returnValue;
  86451. var extendSize = impostor.getObjectExtendSize();
  86452. switch (impostor.type) {
  86453. case BABYLON.PhysicsImpostor.SphereImpostor:
  86454. var radiusX = extendSize.x;
  86455. var radiusY = extendSize.y;
  86456. var radiusZ = extendSize.z;
  86457. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86458. break;
  86459. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86460. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86461. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86462. break;
  86463. case BABYLON.PhysicsImpostor.BoxImpostor:
  86464. var box = extendSize.scale(0.5);
  86465. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86466. break;
  86467. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86468. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86469. returnValue = new this.BJSCANNON.Plane();
  86470. break;
  86471. case BABYLON.PhysicsImpostor.MeshImpostor:
  86472. // should transform the vertex data to world coordinates!!
  86473. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86474. var rawFaces = object.getIndices ? object.getIndices() : [];
  86475. if (!rawVerts)
  86476. return;
  86477. // get only scale! so the object could transform correctly.
  86478. var oldPosition = object.position.clone();
  86479. var oldRotation = object.rotation && object.rotation.clone();
  86480. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86481. object.position.copyFromFloats(0, 0, 0);
  86482. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86483. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86484. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86485. var transform = object.computeWorldMatrix(true);
  86486. // convert rawVerts to object space
  86487. var temp = new Array();
  86488. var index;
  86489. for (index = 0; index < rawVerts.length; index += 3) {
  86490. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86491. }
  86492. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86493. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86494. //now set back the transformation!
  86495. object.position.copyFrom(oldPosition);
  86496. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86497. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86498. break;
  86499. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86500. var oldPosition2 = object.position.clone();
  86501. var oldRotation2 = object.rotation && object.rotation.clone();
  86502. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86503. object.position.copyFromFloats(0, 0, 0);
  86504. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86505. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86506. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86507. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86508. returnValue = this._createHeightmap(object);
  86509. object.position.copyFrom(oldPosition2);
  86510. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86511. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86512. object.computeWorldMatrix(true);
  86513. break;
  86514. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86515. returnValue = new this.BJSCANNON.Particle();
  86516. break;
  86517. }
  86518. return returnValue;
  86519. };
  86520. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86521. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86522. var transform = object.computeWorldMatrix(true);
  86523. // convert rawVerts to object space
  86524. var temp = new Array();
  86525. var index;
  86526. for (index = 0; index < pos.length; index += 3) {
  86527. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86528. }
  86529. pos = temp;
  86530. var matrix = new Array();
  86531. //For now pointDepth will not be used and will be automatically calculated.
  86532. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86533. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86534. var boundingInfo = object.getBoundingInfo();
  86535. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86536. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86537. var elementSize = dim * 2 / arraySize;
  86538. for (var i = 0; i < pos.length; i = i + 3) {
  86539. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86540. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86541. var y = -pos[i + 2] + minY;
  86542. if (!matrix[x]) {
  86543. matrix[x] = [];
  86544. }
  86545. if (!matrix[x][z]) {
  86546. matrix[x][z] = y;
  86547. }
  86548. matrix[x][z] = Math.max(y, matrix[x][z]);
  86549. }
  86550. for (var x = 0; x <= arraySize; ++x) {
  86551. if (!matrix[x]) {
  86552. var loc = 1;
  86553. while (!matrix[(x + loc) % arraySize]) {
  86554. loc++;
  86555. }
  86556. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86557. //console.log("missing x", x);
  86558. }
  86559. for (var z = 0; z <= arraySize; ++z) {
  86560. if (!matrix[x][z]) {
  86561. var loc = 1;
  86562. var newValue;
  86563. while (newValue === undefined) {
  86564. newValue = matrix[x][(z + loc++) % arraySize];
  86565. }
  86566. matrix[x][z] = newValue;
  86567. }
  86568. }
  86569. }
  86570. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86571. elementSize: elementSize
  86572. });
  86573. //For future reference, needed for body transformation
  86574. shape.minY = minY;
  86575. return shape;
  86576. };
  86577. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86578. var object = impostor.object;
  86579. //make sure it is updated...
  86580. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86581. // The delta between the mesh position and the mesh bounding box center
  86582. var bInfo = object.getBoundingInfo();
  86583. if (!bInfo)
  86584. return;
  86585. var center = impostor.getObjectCenter();
  86586. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86587. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86588. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86589. this._tmpPosition.copyFrom(center);
  86590. var quaternion = object.rotationQuaternion;
  86591. if (!quaternion) {
  86592. return;
  86593. }
  86594. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86595. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86596. //-90 DEG in X, precalculated
  86597. quaternion = quaternion.multiply(this._minus90X);
  86598. //Invert! (Precalculated, 90 deg in X)
  86599. //No need to clone. this will never change.
  86600. impostor.setDeltaRotation(this._plus90X);
  86601. }
  86602. //If it is a heightfield, if should be centered.
  86603. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86604. var mesh = object;
  86605. var boundingInfo = mesh.getBoundingInfo();
  86606. //calculate the correct body position:
  86607. var rotationQuaternion = mesh.rotationQuaternion;
  86608. mesh.rotationQuaternion = this._tmpUnityRotation;
  86609. mesh.computeWorldMatrix(true);
  86610. //get original center with no rotation
  86611. var c = center.clone();
  86612. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86613. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86614. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86615. mesh.setPreTransformMatrix(p);
  86616. mesh.computeWorldMatrix(true);
  86617. //calculate the translation
  86618. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86619. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86620. //add it inverted to the delta
  86621. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86622. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86623. //rotation is back
  86624. mesh.rotationQuaternion = rotationQuaternion;
  86625. mesh.setPreTransformMatrix(oldPivot);
  86626. mesh.computeWorldMatrix(true);
  86627. }
  86628. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86629. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86630. //this._tmpPosition.copyFrom(object.position);
  86631. }
  86632. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86633. //Now update the impostor object
  86634. impostor.physicsBody.position.copy(this._tmpPosition);
  86635. impostor.physicsBody.quaternion.copy(quaternion);
  86636. };
  86637. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86638. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86639. if (impostor.object.rotationQuaternion) {
  86640. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86641. }
  86642. };
  86643. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86644. impostor.physicsBody.position.copy(newPosition);
  86645. impostor.physicsBody.quaternion.copy(newRotation);
  86646. };
  86647. CannonJSPlugin.prototype.isSupported = function () {
  86648. return this.BJSCANNON !== undefined;
  86649. };
  86650. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86651. impostor.physicsBody.velocity.copy(velocity);
  86652. };
  86653. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86654. impostor.physicsBody.angularVelocity.copy(velocity);
  86655. };
  86656. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86657. var v = impostor.physicsBody.velocity;
  86658. if (!v) {
  86659. return null;
  86660. }
  86661. return new BABYLON.Vector3(v.x, v.y, v.z);
  86662. };
  86663. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86664. var v = impostor.physicsBody.angularVelocity;
  86665. if (!v) {
  86666. return null;
  86667. }
  86668. return new BABYLON.Vector3(v.x, v.y, v.z);
  86669. };
  86670. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86671. impostor.physicsBody.mass = mass;
  86672. impostor.physicsBody.updateMassProperties();
  86673. };
  86674. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86675. return impostor.physicsBody.mass;
  86676. };
  86677. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86678. return impostor.physicsBody.material.friction;
  86679. };
  86680. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86681. impostor.physicsBody.material.friction = friction;
  86682. };
  86683. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86684. return impostor.physicsBody.material.restitution;
  86685. };
  86686. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86687. impostor.physicsBody.material.restitution = restitution;
  86688. };
  86689. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86690. impostor.physicsBody.sleep();
  86691. };
  86692. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86693. impostor.physicsBody.wakeUp();
  86694. };
  86695. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86696. joint.physicsJoint.distance = maxDistance;
  86697. };
  86698. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86699. // if (!motorIndex) {
  86700. // joint.physicsJoint.enableMotor();
  86701. // }
  86702. // }
  86703. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86704. // if (!motorIndex) {
  86705. // joint.physicsJoint.disableMotor();
  86706. // }
  86707. // }
  86708. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86709. if (!motorIndex) {
  86710. joint.physicsJoint.enableMotor();
  86711. joint.physicsJoint.setMotorSpeed(speed);
  86712. if (maxForce) {
  86713. this.setLimit(joint, maxForce);
  86714. }
  86715. }
  86716. };
  86717. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86718. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86719. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86720. };
  86721. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86722. var body = impostor.physicsBody;
  86723. mesh.position.x = body.position.x;
  86724. mesh.position.y = body.position.y;
  86725. mesh.position.z = body.position.z;
  86726. if (mesh.rotationQuaternion) {
  86727. mesh.rotationQuaternion.x = body.quaternion.x;
  86728. mesh.rotationQuaternion.y = body.quaternion.y;
  86729. mesh.rotationQuaternion.z = body.quaternion.z;
  86730. mesh.rotationQuaternion.w = body.quaternion.w;
  86731. }
  86732. };
  86733. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86734. var shape = impostor.physicsBody.shapes[0];
  86735. return shape.boundingSphereRadius;
  86736. };
  86737. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86738. var shape = impostor.physicsBody.shapes[0];
  86739. result.x = shape.halfExtents.x * 2;
  86740. result.y = shape.halfExtents.y * 2;
  86741. result.z = shape.halfExtents.z * 2;
  86742. };
  86743. CannonJSPlugin.prototype.dispose = function () {
  86744. };
  86745. CannonJSPlugin.prototype._extendNamespace = function () {
  86746. //this will force cannon to execute at least one step when using interpolation
  86747. var step_tmp1 = new this.BJSCANNON.Vec3();
  86748. var Engine = this.BJSCANNON;
  86749. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86750. maxSubSteps = maxSubSteps || 10;
  86751. timeSinceLastCalled = timeSinceLastCalled || 0;
  86752. if (timeSinceLastCalled === 0) {
  86753. this.internalStep(dt);
  86754. this.time += dt;
  86755. }
  86756. else {
  86757. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86758. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86759. var t0 = performance.now();
  86760. for (var i = 0; i !== internalSteps; i++) {
  86761. this.internalStep(dt);
  86762. if (performance.now() - t0 > dt * 1000) {
  86763. break;
  86764. }
  86765. }
  86766. this.time += timeSinceLastCalled;
  86767. var h = this.time % dt;
  86768. var h_div_dt = h / dt;
  86769. var interpvelo = step_tmp1;
  86770. var bodies = this.bodies;
  86771. for (var j = 0; j !== bodies.length; j++) {
  86772. var b = bodies[j];
  86773. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86774. b.position.vsub(b.previousPosition, interpvelo);
  86775. interpvelo.scale(h_div_dt, interpvelo);
  86776. b.position.vadd(interpvelo, b.interpolatedPosition);
  86777. }
  86778. else {
  86779. b.interpolatedPosition.copy(b.position);
  86780. b.interpolatedQuaternion.copy(b.quaternion);
  86781. }
  86782. }
  86783. }
  86784. };
  86785. };
  86786. return CannonJSPlugin;
  86787. }());
  86788. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86789. })(BABYLON || (BABYLON = {}));
  86790. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86791. var BABYLON;
  86792. (function (BABYLON) {
  86793. var OimoJSPlugin = /** @class */ (function () {
  86794. function OimoJSPlugin(iterations) {
  86795. this.name = "OimoJSPlugin";
  86796. this._tmpImpostorsArray = [];
  86797. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86798. this.BJSOIMO = OIMO;
  86799. this.world = new this.BJSOIMO.World({
  86800. iterations: iterations
  86801. });
  86802. this.world.clear();
  86803. }
  86804. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86805. this.world.gravity.copy(gravity);
  86806. };
  86807. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86808. this.world.timeStep = timeStep;
  86809. };
  86810. OimoJSPlugin.prototype.getTimeStep = function () {
  86811. return this.world.timeStep;
  86812. };
  86813. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86814. var _this = this;
  86815. impostors.forEach(function (impostor) {
  86816. impostor.beforeStep();
  86817. });
  86818. this.world.step();
  86819. impostors.forEach(function (impostor) {
  86820. impostor.afterStep();
  86821. //update the ordered impostors array
  86822. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86823. });
  86824. //check for collisions
  86825. var contact = this.world.contacts;
  86826. while (contact !== null) {
  86827. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86828. contact = contact.next;
  86829. continue;
  86830. }
  86831. //is this body colliding with any other? get the impostor
  86832. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86833. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86834. if (!mainImpostor || !collidingImpostor) {
  86835. contact = contact.next;
  86836. continue;
  86837. }
  86838. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86839. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86840. contact = contact.next;
  86841. }
  86842. };
  86843. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86844. var mass = impostor.physicsBody.mass;
  86845. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86846. };
  86847. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86848. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86849. this.applyImpulse(impostor, force, contactPoint);
  86850. };
  86851. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86852. var _this = this;
  86853. //parent-child relationship. Does this impostor has a parent impostor?
  86854. if (impostor.parent) {
  86855. if (impostor.physicsBody) {
  86856. this.removePhysicsBody(impostor);
  86857. //TODO is that needed?
  86858. impostor.forceUpdate();
  86859. }
  86860. return;
  86861. }
  86862. if (impostor.isBodyInitRequired()) {
  86863. var bodyConfig = {
  86864. name: impostor.uniqueId,
  86865. //Oimo must have mass, also for static objects.
  86866. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86867. size: [],
  86868. type: [],
  86869. pos: [],
  86870. posShape: [],
  86871. rot: [],
  86872. rotShape: [],
  86873. move: impostor.getParam("mass") !== 0,
  86874. density: impostor.getParam("mass"),
  86875. friction: impostor.getParam("friction"),
  86876. restitution: impostor.getParam("restitution"),
  86877. //Supporting older versions of Oimo
  86878. world: this.world
  86879. };
  86880. var impostors = [impostor];
  86881. var addToArray = function (parent) {
  86882. if (!parent.getChildMeshes)
  86883. return;
  86884. parent.getChildMeshes().forEach(function (m) {
  86885. if (m.physicsImpostor) {
  86886. impostors.push(m.physicsImpostor);
  86887. //m.physicsImpostor._init();
  86888. }
  86889. });
  86890. };
  86891. addToArray(impostor.object);
  86892. var checkWithEpsilon_1 = function (value) {
  86893. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86894. };
  86895. var globalQuaternion_1 = new BABYLON.Quaternion();
  86896. impostors.forEach(function (i) {
  86897. if (!i.object.rotationQuaternion) {
  86898. return;
  86899. }
  86900. //get the correct bounding box
  86901. var oldQuaternion = i.object.rotationQuaternion;
  86902. globalQuaternion_1 = oldQuaternion.clone();
  86903. var rot = oldQuaternion.toEulerAngles();
  86904. var extendSize = i.getObjectExtendSize();
  86905. var radToDeg = 57.295779513082320876;
  86906. if (i === impostor) {
  86907. var center = impostor.getObjectCenter();
  86908. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86909. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86910. //Can also use Array.prototype.push.apply
  86911. bodyConfig.pos.push(center.x);
  86912. bodyConfig.pos.push(center.y);
  86913. bodyConfig.pos.push(center.z);
  86914. bodyConfig.posShape.push(0, 0, 0);
  86915. //tmp solution
  86916. bodyConfig.rot.push(0);
  86917. bodyConfig.rot.push(0);
  86918. bodyConfig.rot.push(0);
  86919. bodyConfig.rotShape.push(0, 0, 0);
  86920. }
  86921. else {
  86922. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86923. bodyConfig.posShape.push(localPosition.x);
  86924. bodyConfig.posShape.push(localPosition.y);
  86925. bodyConfig.posShape.push(localPosition.z);
  86926. bodyConfig.pos.push(0, 0, 0);
  86927. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86928. bodyConfig.rot.push(0);
  86929. bodyConfig.rot.push(0);
  86930. bodyConfig.rot.push(0);
  86931. bodyConfig.rotShape.push(rot.x * radToDeg);
  86932. bodyConfig.rotShape.push(rot.y * radToDeg);
  86933. bodyConfig.rotShape.push(rot.z * radToDeg);
  86934. }
  86935. // register mesh
  86936. switch (i.type) {
  86937. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86938. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86939. case BABYLON.PhysicsImpostor.SphereImpostor:
  86940. var radiusX = extendSize.x;
  86941. var radiusY = extendSize.y;
  86942. var radiusZ = extendSize.z;
  86943. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86944. bodyConfig.type.push('sphere');
  86945. //due to the way oimo works with compounds, add 3 times
  86946. bodyConfig.size.push(size);
  86947. bodyConfig.size.push(size);
  86948. bodyConfig.size.push(size);
  86949. break;
  86950. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86951. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86952. var sizeY = checkWithEpsilon_1(extendSize.y);
  86953. bodyConfig.type.push('cylinder');
  86954. bodyConfig.size.push(sizeX);
  86955. bodyConfig.size.push(sizeY);
  86956. //due to the way oimo works with compounds, add one more value.
  86957. bodyConfig.size.push(sizeY);
  86958. break;
  86959. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86960. case BABYLON.PhysicsImpostor.BoxImpostor:
  86961. default:
  86962. var sizeX = checkWithEpsilon_1(extendSize.x);
  86963. var sizeY = checkWithEpsilon_1(extendSize.y);
  86964. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86965. bodyConfig.type.push('box');
  86966. //if (i === impostor) {
  86967. bodyConfig.size.push(sizeX);
  86968. bodyConfig.size.push(sizeY);
  86969. bodyConfig.size.push(sizeZ);
  86970. //} else {
  86971. // bodyConfig.size.push(0,0,0);
  86972. //}
  86973. break;
  86974. }
  86975. //actually not needed, but hey...
  86976. i.object.rotationQuaternion = oldQuaternion;
  86977. });
  86978. impostor.physicsBody = this.world.add(bodyConfig);
  86979. // set the quaternion, ignoring the previously defined (euler) rotation
  86980. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  86981. // update with delta 0, so the body will reveive the new rotation.
  86982. impostor.physicsBody.updatePosition(0);
  86983. }
  86984. else {
  86985. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86986. }
  86987. impostor.setDeltaPosition(this._tmpPositionVector);
  86988. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86989. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86990. };
  86991. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86992. //impostor.physicsBody.dispose();
  86993. //Same as : (older oimo versions)
  86994. this.world.removeRigidBody(impostor.physicsBody);
  86995. };
  86996. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86997. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86998. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86999. if (!mainBody || !connectedBody) {
  87000. return;
  87001. }
  87002. var jointData = impostorJoint.joint.jointData;
  87003. var options = jointData.nativeParams || {};
  87004. var type;
  87005. var nativeJointData = {
  87006. body1: mainBody,
  87007. body2: connectedBody,
  87008. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87009. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87010. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87011. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87012. min: options.min,
  87013. max: options.max,
  87014. collision: options.collision || jointData.collision,
  87015. spring: options.spring,
  87016. //supporting older version of Oimo
  87017. world: this.world
  87018. };
  87019. switch (impostorJoint.joint.type) {
  87020. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87021. type = "jointBall";
  87022. break;
  87023. case BABYLON.PhysicsJoint.SpringJoint:
  87024. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87025. var springData = jointData;
  87026. nativeJointData.min = springData.length || nativeJointData.min;
  87027. //Max should also be set, just make sure it is at least min
  87028. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87029. case BABYLON.PhysicsJoint.DistanceJoint:
  87030. type = "jointDistance";
  87031. nativeJointData.max = jointData.maxDistance;
  87032. break;
  87033. case BABYLON.PhysicsJoint.PrismaticJoint:
  87034. type = "jointPrisme";
  87035. break;
  87036. case BABYLON.PhysicsJoint.SliderJoint:
  87037. type = "jointSlide";
  87038. break;
  87039. case BABYLON.PhysicsJoint.WheelJoint:
  87040. type = "jointWheel";
  87041. break;
  87042. case BABYLON.PhysicsJoint.HingeJoint:
  87043. default:
  87044. type = "jointHinge";
  87045. break;
  87046. }
  87047. nativeJointData.type = type;
  87048. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87049. };
  87050. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87051. //Bug in Oimo prevents us from disposing a joint in the playground
  87052. //joint.joint.physicsJoint.dispose();
  87053. //So we will bruteforce it!
  87054. try {
  87055. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87056. }
  87057. catch (e) {
  87058. BABYLON.Tools.Warn(e);
  87059. }
  87060. };
  87061. OimoJSPlugin.prototype.isSupported = function () {
  87062. return this.BJSOIMO !== undefined;
  87063. };
  87064. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87065. if (!impostor.physicsBody.sleeping) {
  87066. //TODO check that
  87067. /*if (impostor.physicsBody.shapes.next) {
  87068. var parentShape = this._getLastShape(impostor.physicsBody);
  87069. impostor.object.position.copyFrom(parentShape.position);
  87070. console.log(parentShape.position);
  87071. } else {*/
  87072. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87073. //}
  87074. if (impostor.object.rotationQuaternion) {
  87075. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87076. }
  87077. }
  87078. };
  87079. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87080. var body = impostor.physicsBody;
  87081. body.position.copy(newPosition);
  87082. body.orientation.copy(newRotation);
  87083. body.syncShapes();
  87084. body.awake();
  87085. };
  87086. /*private _getLastShape(body: any): any {
  87087. var lastShape = body.shapes;
  87088. while (lastShape.next) {
  87089. lastShape = lastShape.next;
  87090. }
  87091. return lastShape;
  87092. }*/
  87093. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87094. impostor.physicsBody.linearVelocity.copy(velocity);
  87095. };
  87096. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87097. impostor.physicsBody.angularVelocity.copy(velocity);
  87098. };
  87099. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87100. var v = impostor.physicsBody.linearVelocity;
  87101. if (!v) {
  87102. return null;
  87103. }
  87104. return new BABYLON.Vector3(v.x, v.y, v.z);
  87105. };
  87106. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87107. var v = impostor.physicsBody.angularVelocity;
  87108. if (!v) {
  87109. return null;
  87110. }
  87111. return new BABYLON.Vector3(v.x, v.y, v.z);
  87112. };
  87113. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87114. var staticBody = mass === 0;
  87115. //this will actually set the body's density and not its mass.
  87116. //But this is how oimo treats the mass variable.
  87117. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87118. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87119. };
  87120. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87121. return impostor.physicsBody.shapes.density;
  87122. };
  87123. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87124. return impostor.physicsBody.shapes.friction;
  87125. };
  87126. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87127. impostor.physicsBody.shapes.friction = friction;
  87128. };
  87129. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87130. return impostor.physicsBody.shapes.restitution;
  87131. };
  87132. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87133. impostor.physicsBody.shapes.restitution = restitution;
  87134. };
  87135. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87136. impostor.physicsBody.sleep();
  87137. };
  87138. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87139. impostor.physicsBody.awake();
  87140. };
  87141. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87142. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87143. if (minDistance !== void 0) {
  87144. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87145. }
  87146. };
  87147. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87148. //TODO separate rotational and transational motors.
  87149. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87150. if (motor) {
  87151. motor.setMotor(speed, maxForce);
  87152. }
  87153. };
  87154. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87155. //TODO separate rotational and transational motors.
  87156. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87157. if (motor) {
  87158. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87159. }
  87160. };
  87161. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87162. var body = impostor.physicsBody;
  87163. mesh.position.x = body.position.x;
  87164. mesh.position.y = body.position.y;
  87165. mesh.position.z = body.position.z;
  87166. if (mesh.rotationQuaternion) {
  87167. mesh.rotationQuaternion.x = body.orientation.x;
  87168. mesh.rotationQuaternion.y = body.orientation.y;
  87169. mesh.rotationQuaternion.z = body.orientation.z;
  87170. mesh.rotationQuaternion.w = body.orientation.s;
  87171. }
  87172. };
  87173. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87174. return impostor.physicsBody.shapes.radius;
  87175. };
  87176. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87177. var shape = impostor.physicsBody.shapes;
  87178. result.x = shape.halfWidth * 2;
  87179. result.y = shape.halfHeight * 2;
  87180. result.z = shape.halfDepth * 2;
  87181. };
  87182. OimoJSPlugin.prototype.dispose = function () {
  87183. this.world.clear();
  87184. };
  87185. return OimoJSPlugin;
  87186. }());
  87187. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87188. })(BABYLON || (BABYLON = {}));
  87189. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87190. var BABYLON;
  87191. (function (BABYLON) {
  87192. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87193. // All values and structures referenced from:
  87194. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87195. var DDS_MAGIC = 0x20534444;
  87196. var
  87197. //DDSD_CAPS = 0x1,
  87198. //DDSD_HEIGHT = 0x2,
  87199. //DDSD_WIDTH = 0x4,
  87200. //DDSD_PITCH = 0x8,
  87201. //DDSD_PIXELFORMAT = 0x1000,
  87202. DDSD_MIPMAPCOUNT = 0x20000;
  87203. //DDSD_LINEARSIZE = 0x80000,
  87204. //DDSD_DEPTH = 0x800000;
  87205. // var DDSCAPS_COMPLEX = 0x8,
  87206. // DDSCAPS_MIPMAP = 0x400000,
  87207. // DDSCAPS_TEXTURE = 0x1000;
  87208. var DDSCAPS2_CUBEMAP = 0x200;
  87209. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87210. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87211. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87212. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87213. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87214. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87215. // DDSCAPS2_VOLUME = 0x200000;
  87216. var
  87217. //DDPF_ALPHAPIXELS = 0x1,
  87218. //DDPF_ALPHA = 0x2,
  87219. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87220. //DDPF_YUV = 0x200,
  87221. DDPF_LUMINANCE = 0x20000;
  87222. function FourCCToInt32(value) {
  87223. return value.charCodeAt(0) +
  87224. (value.charCodeAt(1) << 8) +
  87225. (value.charCodeAt(2) << 16) +
  87226. (value.charCodeAt(3) << 24);
  87227. }
  87228. function Int32ToFourCC(value) {
  87229. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87230. }
  87231. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87232. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87233. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87234. var FOURCC_DX10 = FourCCToInt32("DX10");
  87235. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87236. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87237. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87238. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87239. var headerLengthInt = 31; // The header length in 32 bit ints
  87240. // Offsets into the header array
  87241. var off_magic = 0;
  87242. var off_size = 1;
  87243. var off_flags = 2;
  87244. var off_height = 3;
  87245. var off_width = 4;
  87246. var off_mipmapCount = 7;
  87247. var off_pfFlags = 20;
  87248. var off_pfFourCC = 21;
  87249. var off_RGBbpp = 22;
  87250. var off_RMask = 23;
  87251. var off_GMask = 24;
  87252. var off_BMask = 25;
  87253. var off_AMask = 26;
  87254. // var off_caps1 = 27;
  87255. var off_caps2 = 28;
  87256. // var off_caps3 = 29;
  87257. // var off_caps4 = 30;
  87258. var off_dxgiFormat = 32;
  87259. ;
  87260. var DDSTools = /** @class */ (function () {
  87261. function DDSTools() {
  87262. }
  87263. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87264. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87265. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87266. var mipmapCount = 1;
  87267. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87268. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87269. }
  87270. var fourCC = header[off_pfFourCC];
  87271. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87272. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87273. switch (fourCC) {
  87274. case FOURCC_D3DFMT_R16G16B16A16F:
  87275. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87276. break;
  87277. case FOURCC_D3DFMT_R32G32B32A32F:
  87278. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87279. break;
  87280. case FOURCC_DX10:
  87281. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87282. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87283. break;
  87284. }
  87285. }
  87286. return {
  87287. width: header[off_width],
  87288. height: header[off_height],
  87289. mipmapCount: mipmapCount,
  87290. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87291. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87292. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87293. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87294. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87295. dxgiFormat: dxgiFormat,
  87296. textureType: textureType
  87297. };
  87298. };
  87299. DDSTools._ToHalfFloat = function (value) {
  87300. if (!DDSTools._FloatView) {
  87301. DDSTools._FloatView = new Float32Array(1);
  87302. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87303. }
  87304. DDSTools._FloatView[0] = value;
  87305. var x = DDSTools._Int32View[0];
  87306. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87307. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87308. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87309. /* If zero, or denormal, or exponent underflows too much for a denormal
  87310. * half, return signed zero. */
  87311. if (e < 103) {
  87312. return bits;
  87313. }
  87314. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87315. if (e > 142) {
  87316. bits |= 0x7c00;
  87317. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87318. * not Inf, so make sure we set one mantissa bit too. */
  87319. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87320. return bits;
  87321. }
  87322. /* If exponent underflows but not too much, return a denormal */
  87323. if (e < 113) {
  87324. m |= 0x0800;
  87325. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87326. * to 1, which is OK. */
  87327. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87328. return bits;
  87329. }
  87330. bits |= ((e - 112) << 10) | (m >> 1);
  87331. bits += m & 1;
  87332. return bits;
  87333. };
  87334. DDSTools._FromHalfFloat = function (value) {
  87335. var s = (value & 0x8000) >> 15;
  87336. var e = (value & 0x7C00) >> 10;
  87337. var f = value & 0x03FF;
  87338. if (e === 0) {
  87339. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87340. }
  87341. else if (e == 0x1F) {
  87342. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87343. }
  87344. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87345. };
  87346. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87347. var destArray = new Float32Array(dataLength);
  87348. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87349. var index = 0;
  87350. for (var y = 0; y < height; y++) {
  87351. for (var x = 0; x < width; x++) {
  87352. var srcPos = (x + y * width) * 4;
  87353. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87354. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87355. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87356. if (DDSTools.StoreLODInAlphaChannel) {
  87357. destArray[index + 3] = lod;
  87358. }
  87359. else {
  87360. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87361. }
  87362. index += 4;
  87363. }
  87364. }
  87365. return destArray;
  87366. };
  87367. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87368. if (DDSTools.StoreLODInAlphaChannel) {
  87369. var destArray = new Uint16Array(dataLength);
  87370. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87371. var index = 0;
  87372. for (var y = 0; y < height; y++) {
  87373. for (var x = 0; x < width; x++) {
  87374. var srcPos = (x + y * width) * 4;
  87375. destArray[index] = srcData[srcPos];
  87376. destArray[index + 1] = srcData[srcPos + 1];
  87377. destArray[index + 2] = srcData[srcPos + 2];
  87378. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87379. index += 4;
  87380. }
  87381. }
  87382. return destArray;
  87383. }
  87384. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87385. };
  87386. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87387. if (DDSTools.StoreLODInAlphaChannel) {
  87388. var destArray = new Float32Array(dataLength);
  87389. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87390. var index = 0;
  87391. for (var y = 0; y < height; y++) {
  87392. for (var x = 0; x < width; x++) {
  87393. var srcPos = (x + y * width) * 4;
  87394. destArray[index] = srcData[srcPos];
  87395. destArray[index + 1] = srcData[srcPos + 1];
  87396. destArray[index + 2] = srcData[srcPos + 2];
  87397. destArray[index + 3] = lod;
  87398. index += 4;
  87399. }
  87400. }
  87401. return destArray;
  87402. }
  87403. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87404. };
  87405. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87406. var destArray = new Uint8Array(dataLength);
  87407. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87408. var index = 0;
  87409. for (var y = 0; y < height; y++) {
  87410. for (var x = 0; x < width; x++) {
  87411. var srcPos = (x + y * width) * 4;
  87412. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87413. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87414. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87415. if (DDSTools.StoreLODInAlphaChannel) {
  87416. destArray[index + 3] = lod;
  87417. }
  87418. else {
  87419. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87420. }
  87421. index += 4;
  87422. }
  87423. }
  87424. return destArray;
  87425. };
  87426. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87427. var destArray = new Uint8Array(dataLength);
  87428. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87429. var index = 0;
  87430. for (var y = 0; y < height; y++) {
  87431. for (var x = 0; x < width; x++) {
  87432. var srcPos = (x + y * width) * 4;
  87433. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87434. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87435. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87436. if (DDSTools.StoreLODInAlphaChannel) {
  87437. destArray[index + 3] = lod;
  87438. }
  87439. else {
  87440. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87441. }
  87442. index += 4;
  87443. }
  87444. }
  87445. return destArray;
  87446. };
  87447. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87448. var byteArray = new Uint8Array(dataLength);
  87449. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87450. var index = 0;
  87451. for (var y = 0; y < height; y++) {
  87452. for (var x = 0; x < width; x++) {
  87453. var srcPos = (x + y * width) * 4;
  87454. byteArray[index] = srcData[srcPos + rOffset];
  87455. byteArray[index + 1] = srcData[srcPos + gOffset];
  87456. byteArray[index + 2] = srcData[srcPos + bOffset];
  87457. byteArray[index + 3] = srcData[srcPos + aOffset];
  87458. index += 4;
  87459. }
  87460. }
  87461. return byteArray;
  87462. };
  87463. DDSTools._ExtractLongWordOrder = function (value) {
  87464. if (value === 0 || value === 255 || value === -16777216) {
  87465. return 0;
  87466. }
  87467. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87468. };
  87469. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87470. var byteArray = new Uint8Array(dataLength);
  87471. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87472. var index = 0;
  87473. for (var y = 0; y < height; y++) {
  87474. for (var x = 0; x < width; x++) {
  87475. var srcPos = (x + y * width) * 3;
  87476. byteArray[index] = srcData[srcPos + rOffset];
  87477. byteArray[index + 1] = srcData[srcPos + gOffset];
  87478. byteArray[index + 2] = srcData[srcPos + bOffset];
  87479. index += 3;
  87480. }
  87481. }
  87482. return byteArray;
  87483. };
  87484. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87485. var byteArray = new Uint8Array(dataLength);
  87486. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87487. var index = 0;
  87488. for (var y = 0; y < height; y++) {
  87489. for (var x = 0; x < width; x++) {
  87490. var srcPos = (x + y * width);
  87491. byteArray[index] = srcData[srcPos];
  87492. index++;
  87493. }
  87494. }
  87495. return byteArray;
  87496. };
  87497. /**
  87498. * Uploads DDS Levels to a Babylon Texture
  87499. * @hidden
  87500. */
  87501. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87502. if (lodIndex === void 0) { lodIndex = -1; }
  87503. var sphericalPolynomialFaces = null;
  87504. if (info.sphericalPolynomial) {
  87505. sphericalPolynomialFaces = new Array();
  87506. }
  87507. var ext = engine.getCaps().s3tc;
  87508. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87509. var fourCC, width, height, dataLength = 0, dataOffset;
  87510. var byteArray, mipmapCount, mip;
  87511. var internalCompressedFormat = 0;
  87512. var blockBytes = 1;
  87513. if (header[off_magic] !== DDS_MAGIC) {
  87514. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87515. return;
  87516. }
  87517. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87518. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87519. return;
  87520. }
  87521. if (info.isCompressed && !ext) {
  87522. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87523. return;
  87524. }
  87525. var bpp = header[off_RGBbpp];
  87526. dataOffset = header[off_size] + 4;
  87527. var computeFormats = false;
  87528. if (info.isFourCC) {
  87529. fourCC = header[off_pfFourCC];
  87530. switch (fourCC) {
  87531. case FOURCC_DXT1:
  87532. blockBytes = 8;
  87533. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87534. break;
  87535. case FOURCC_DXT3:
  87536. blockBytes = 16;
  87537. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87538. break;
  87539. case FOURCC_DXT5:
  87540. blockBytes = 16;
  87541. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87542. break;
  87543. case FOURCC_D3DFMT_R16G16B16A16F:
  87544. computeFormats = true;
  87545. break;
  87546. case FOURCC_D3DFMT_R32G32B32A32F:
  87547. computeFormats = true;
  87548. break;
  87549. case FOURCC_DX10:
  87550. // There is an additionnal header so dataOffset need to be changed
  87551. dataOffset += 5 * 4; // 5 uints
  87552. var supported = false;
  87553. switch (info.dxgiFormat) {
  87554. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87555. computeFormats = true;
  87556. supported = true;
  87557. break;
  87558. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87559. info.isRGB = true;
  87560. info.isFourCC = false;
  87561. bpp = 32;
  87562. supported = true;
  87563. break;
  87564. }
  87565. if (supported) {
  87566. break;
  87567. }
  87568. default:
  87569. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87570. return;
  87571. }
  87572. }
  87573. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87574. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87575. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87576. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87577. if (computeFormats) {
  87578. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87579. }
  87580. mipmapCount = 1;
  87581. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87582. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87583. }
  87584. for (var face = 0; face < faces; face++) {
  87585. width = header[off_width];
  87586. height = header[off_height];
  87587. for (mip = 0; mip < mipmapCount; ++mip) {
  87588. if (lodIndex === -1 || lodIndex === mip) {
  87589. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87590. var i = (lodIndex === -1) ? mip : 0;
  87591. if (!info.isCompressed && info.isFourCC) {
  87592. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87593. dataLength = width * height * 4;
  87594. var floatArray = null;
  87595. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87596. if (bpp === 128) {
  87597. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87598. if (sphericalPolynomialFaces && i == 0) {
  87599. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87600. }
  87601. }
  87602. else if (bpp === 64) {
  87603. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87604. if (sphericalPolynomialFaces && i == 0) {
  87605. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87606. }
  87607. }
  87608. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87609. }
  87610. else {
  87611. if (bpp === 128) {
  87612. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87613. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87614. if (sphericalPolynomialFaces && i == 0) {
  87615. sphericalPolynomialFaces.push(floatArray);
  87616. }
  87617. }
  87618. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87619. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87620. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87621. if (sphericalPolynomialFaces && i == 0) {
  87622. sphericalPolynomialFaces.push(floatArray);
  87623. }
  87624. }
  87625. else { // 64
  87626. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87627. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87628. if (sphericalPolynomialFaces && i == 0) {
  87629. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87630. }
  87631. }
  87632. }
  87633. if (floatArray) {
  87634. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  87635. }
  87636. }
  87637. else if (info.isRGB) {
  87638. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87639. if (bpp === 24) {
  87640. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  87641. dataLength = width * height * 3;
  87642. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87643. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87644. }
  87645. else { // 32
  87646. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87647. dataLength = width * height * 4;
  87648. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87649. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87650. }
  87651. }
  87652. else if (info.isLuminance) {
  87653. var unpackAlignment = engine._getUnpackAlignement();
  87654. var unpaddedRowSize = width;
  87655. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87656. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87657. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87658. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  87659. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87660. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87661. }
  87662. else {
  87663. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87664. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87665. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87666. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  87667. }
  87668. }
  87669. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87670. width *= 0.5;
  87671. height *= 0.5;
  87672. width = Math.max(1.0, width);
  87673. height = Math.max(1.0, height);
  87674. }
  87675. if (currentFace !== undefined) {
  87676. // Loading a single face
  87677. break;
  87678. }
  87679. }
  87680. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87681. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87682. size: header[off_width],
  87683. right: sphericalPolynomialFaces[0],
  87684. left: sphericalPolynomialFaces[1],
  87685. up: sphericalPolynomialFaces[2],
  87686. down: sphericalPolynomialFaces[3],
  87687. front: sphericalPolynomialFaces[4],
  87688. back: sphericalPolynomialFaces[5],
  87689. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87690. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87691. gammaSpace: false,
  87692. });
  87693. }
  87694. else {
  87695. info.sphericalPolynomial = undefined;
  87696. }
  87697. };
  87698. DDSTools.StoreLODInAlphaChannel = false;
  87699. return DDSTools;
  87700. }());
  87701. BABYLON.DDSTools = DDSTools;
  87702. })(BABYLON || (BABYLON = {}));
  87703. //# sourceMappingURL=babylon.dds.js.map
  87704. var BABYLON;
  87705. (function (BABYLON) {
  87706. /**
  87707. * Implementation of the DDS Texture Loader.
  87708. */
  87709. var DDSTextureLoader = /** @class */ (function () {
  87710. function DDSTextureLoader() {
  87711. /**
  87712. * Defines wether the loader supports cascade loading the different faces.
  87713. */
  87714. this.supportCascades = true;
  87715. }
  87716. /**
  87717. * This returns if the loader support the current file information.
  87718. * @param extension defines the file extension of the file being loaded
  87719. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87720. * @param fallback defines the fallback internal texture if any
  87721. * @param isBase64 defines whether the texture is encoded as a base64
  87722. * @param isBuffer defines whether the texture data are stored as a buffer
  87723. * @returns true if the loader can load the specified file
  87724. */
  87725. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  87726. return extension.indexOf(".dds") === 0;
  87727. };
  87728. /**
  87729. * Transform the url before loading if required.
  87730. * @param rootUrl the url of the texture
  87731. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87732. * @returns the transformed texture
  87733. */
  87734. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  87735. return rootUrl;
  87736. };
  87737. /**
  87738. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  87739. * @param rootUrl the url of the texture
  87740. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87741. * @returns the fallback texture
  87742. */
  87743. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  87744. return null;
  87745. };
  87746. /**
  87747. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  87748. * @param data contains the texture data
  87749. * @param texture defines the BabylonJS internal texture
  87750. * @param createPolynomials will be true if polynomials have been requested
  87751. * @param onLoad defines the callback to trigger once the texture is ready
  87752. * @param onError defines the callback to trigger in case of error
  87753. */
  87754. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  87755. var engine = texture.getEngine();
  87756. var info;
  87757. var loadMipmap = false;
  87758. if (Array.isArray(imgs)) {
  87759. for (var index = 0; index < imgs.length; index++) {
  87760. var data_1 = imgs[index];
  87761. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  87762. texture.width = info.width;
  87763. texture.height = info.height;
  87764. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87765. engine._unpackFlipY(info.isCompressed);
  87766. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  87767. if (!info.isFourCC && info.mipmapCount === 1) {
  87768. engine.generateMipMapsForCubemap(texture);
  87769. }
  87770. }
  87771. }
  87772. else {
  87773. var data = imgs;
  87774. info = BABYLON.DDSTools.GetDDSInfo(data);
  87775. texture.width = info.width;
  87776. texture.height = info.height;
  87777. if (createPolynomials) {
  87778. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  87779. }
  87780. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87781. engine._unpackFlipY(info.isCompressed);
  87782. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  87783. if (!info.isFourCC && info.mipmapCount === 1) {
  87784. engine.generateMipMapsForCubemap(texture);
  87785. }
  87786. }
  87787. engine._setCubeMapTextureParams(loadMipmap);
  87788. texture.isReady = true;
  87789. if (onLoad) {
  87790. onLoad({ isDDS: true, width: texture.width, info: info, imgs: imgs, texture: texture });
  87791. }
  87792. };
  87793. /**
  87794. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  87795. * @param data contains the texture data
  87796. * @param texture defines the BabylonJS internal texture
  87797. * @param callback defines the method to call once ready to upload
  87798. */
  87799. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  87800. var info = BABYLON.DDSTools.GetDDSInfo(data);
  87801. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  87802. callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {
  87803. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  87804. });
  87805. };
  87806. return DDSTextureLoader;
  87807. }());
  87808. // Register the loader.
  87809. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  87810. })(BABYLON || (BABYLON = {}));
  87811. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  87812. var BABYLON;
  87813. (function (BABYLON) {
  87814. /*
  87815. * Based on jsTGALoader - Javascript loader for TGA file
  87816. * By Vincent Thibault
  87817. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87818. */
  87819. var TGATools = /** @class */ (function () {
  87820. function TGATools() {
  87821. }
  87822. TGATools.GetTGAHeader = function (data) {
  87823. var offset = 0;
  87824. var header = {
  87825. id_length: data[offset++],
  87826. colormap_type: data[offset++],
  87827. image_type: data[offset++],
  87828. colormap_index: data[offset++] | data[offset++] << 8,
  87829. colormap_length: data[offset++] | data[offset++] << 8,
  87830. colormap_size: data[offset++],
  87831. origin: [
  87832. data[offset++] | data[offset++] << 8,
  87833. data[offset++] | data[offset++] << 8
  87834. ],
  87835. width: data[offset++] | data[offset++] << 8,
  87836. height: data[offset++] | data[offset++] << 8,
  87837. pixel_size: data[offset++],
  87838. flags: data[offset++]
  87839. };
  87840. return header;
  87841. };
  87842. /**
  87843. * Uploads TGA content to a Babylon Texture
  87844. * @hidden
  87845. */
  87846. TGATools.UploadContent = function (texture, data) {
  87847. // Not enough data to contain header ?
  87848. if (data.length < 19) {
  87849. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87850. return;
  87851. }
  87852. // Read Header
  87853. var offset = 18;
  87854. var header = TGATools.GetTGAHeader(data);
  87855. // Assume it's a valid Targa file.
  87856. if (header.id_length + offset > data.length) {
  87857. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87858. return;
  87859. }
  87860. // Skip not needed data
  87861. offset += header.id_length;
  87862. var use_rle = false;
  87863. var use_pal = false;
  87864. var use_grey = false;
  87865. // Get some informations.
  87866. switch (header.image_type) {
  87867. case TGATools._TYPE_RLE_INDEXED:
  87868. use_rle = true;
  87869. case TGATools._TYPE_INDEXED:
  87870. use_pal = true;
  87871. break;
  87872. case TGATools._TYPE_RLE_RGB:
  87873. use_rle = true;
  87874. case TGATools._TYPE_RGB:
  87875. // use_rgb = true;
  87876. break;
  87877. case TGATools._TYPE_RLE_GREY:
  87878. use_rle = true;
  87879. case TGATools._TYPE_GREY:
  87880. use_grey = true;
  87881. break;
  87882. }
  87883. var pixel_data;
  87884. // var numAlphaBits = header.flags & 0xf;
  87885. var pixel_size = header.pixel_size >> 3;
  87886. var pixel_total = header.width * header.height * pixel_size;
  87887. // Read palettes
  87888. var palettes;
  87889. if (use_pal) {
  87890. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87891. }
  87892. // Read LRE
  87893. if (use_rle) {
  87894. pixel_data = new Uint8Array(pixel_total);
  87895. var c, count, i;
  87896. var localOffset = 0;
  87897. var pixels = new Uint8Array(pixel_size);
  87898. while (offset < pixel_total && localOffset < pixel_total) {
  87899. c = data[offset++];
  87900. count = (c & 0x7f) + 1;
  87901. // RLE pixels
  87902. if (c & 0x80) {
  87903. // Bind pixel tmp array
  87904. for (i = 0; i < pixel_size; ++i) {
  87905. pixels[i] = data[offset++];
  87906. }
  87907. // Copy pixel array
  87908. for (i = 0; i < count; ++i) {
  87909. pixel_data.set(pixels, localOffset + i * pixel_size);
  87910. }
  87911. localOffset += pixel_size * count;
  87912. }
  87913. // Raw pixels
  87914. else {
  87915. count *= pixel_size;
  87916. for (i = 0; i < count; ++i) {
  87917. pixel_data[localOffset + i] = data[offset++];
  87918. }
  87919. localOffset += count;
  87920. }
  87921. }
  87922. }
  87923. // RAW Pixels
  87924. else {
  87925. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87926. }
  87927. // Load to texture
  87928. var x_start, y_start, x_step, y_step, y_end, x_end;
  87929. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87930. default:
  87931. case TGATools._ORIGIN_UL:
  87932. x_start = 0;
  87933. x_step = 1;
  87934. x_end = header.width;
  87935. y_start = 0;
  87936. y_step = 1;
  87937. y_end = header.height;
  87938. break;
  87939. case TGATools._ORIGIN_BL:
  87940. x_start = 0;
  87941. x_step = 1;
  87942. x_end = header.width;
  87943. y_start = header.height - 1;
  87944. y_step = -1;
  87945. y_end = -1;
  87946. break;
  87947. case TGATools._ORIGIN_UR:
  87948. x_start = header.width - 1;
  87949. x_step = -1;
  87950. x_end = -1;
  87951. y_start = 0;
  87952. y_step = 1;
  87953. y_end = header.height;
  87954. break;
  87955. case TGATools._ORIGIN_BR:
  87956. x_start = header.width - 1;
  87957. x_step = -1;
  87958. x_end = -1;
  87959. y_start = header.height - 1;
  87960. y_step = -1;
  87961. y_end = -1;
  87962. break;
  87963. }
  87964. // Load the specify method
  87965. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87966. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87967. var engine = texture.getEngine();
  87968. engine._uploadDataToTextureDirectly(texture, imageData);
  87969. };
  87970. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87971. var image = pixel_data, colormap = palettes;
  87972. var width = header.width, height = header.height;
  87973. var color, i = 0, x, y;
  87974. var imageData = new Uint8Array(width * height * 4);
  87975. for (y = y_start; y !== y_end; y += y_step) {
  87976. for (x = x_start; x !== x_end; x += x_step, i++) {
  87977. color = image[i];
  87978. imageData[(x + width * y) * 4 + 3] = 255;
  87979. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  87980. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  87981. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  87982. }
  87983. }
  87984. return imageData;
  87985. };
  87986. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87987. var image = pixel_data;
  87988. var width = header.width, height = header.height;
  87989. var color, i = 0, x, y;
  87990. var imageData = new Uint8Array(width * height * 4);
  87991. for (y = y_start; y !== y_end; y += y_step) {
  87992. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87993. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  87994. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  87995. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  87996. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  87997. imageData[(x + width * y) * 4 + 0] = r;
  87998. imageData[(x + width * y) * 4 + 1] = g;
  87999. imageData[(x + width * y) * 4 + 2] = b;
  88000. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  88001. }
  88002. }
  88003. return imageData;
  88004. };
  88005. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88006. var image = pixel_data;
  88007. var width = header.width, height = header.height;
  88008. var i = 0, x, y;
  88009. var imageData = new Uint8Array(width * height * 4);
  88010. for (y = y_start; y !== y_end; y += y_step) {
  88011. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  88012. imageData[(x + width * y) * 4 + 3] = 255;
  88013. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88014. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88015. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88016. }
  88017. }
  88018. return imageData;
  88019. };
  88020. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88021. var image = pixel_data;
  88022. var width = header.width, height = header.height;
  88023. var i = 0, x, y;
  88024. var imageData = new Uint8Array(width * height * 4);
  88025. for (y = y_start; y !== y_end; y += y_step) {
  88026. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  88027. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88028. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88029. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88030. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  88031. }
  88032. }
  88033. return imageData;
  88034. };
  88035. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88036. var image = pixel_data;
  88037. var width = header.width, height = header.height;
  88038. var color, i = 0, x, y;
  88039. var imageData = new Uint8Array(width * height * 4);
  88040. for (y = y_start; y !== y_end; y += y_step) {
  88041. for (x = x_start; x !== x_end; x += x_step, i++) {
  88042. color = image[i];
  88043. imageData[(x + width * y) * 4 + 0] = color;
  88044. imageData[(x + width * y) * 4 + 1] = color;
  88045. imageData[(x + width * y) * 4 + 2] = color;
  88046. imageData[(x + width * y) * 4 + 3] = 255;
  88047. }
  88048. }
  88049. return imageData;
  88050. };
  88051. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88052. var image = pixel_data;
  88053. var width = header.width, height = header.height;
  88054. var i = 0, x, y;
  88055. var imageData = new Uint8Array(width * height * 4);
  88056. for (y = y_start; y !== y_end; y += y_step) {
  88057. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88058. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  88059. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  88060. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88061. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  88062. }
  88063. }
  88064. return imageData;
  88065. };
  88066. //private static _TYPE_NO_DATA = 0;
  88067. TGATools._TYPE_INDEXED = 1;
  88068. TGATools._TYPE_RGB = 2;
  88069. TGATools._TYPE_GREY = 3;
  88070. TGATools._TYPE_RLE_INDEXED = 9;
  88071. TGATools._TYPE_RLE_RGB = 10;
  88072. TGATools._TYPE_RLE_GREY = 11;
  88073. TGATools._ORIGIN_MASK = 0x30;
  88074. TGATools._ORIGIN_SHIFT = 0x04;
  88075. TGATools._ORIGIN_BL = 0x00;
  88076. TGATools._ORIGIN_BR = 0x01;
  88077. TGATools._ORIGIN_UL = 0x02;
  88078. TGATools._ORIGIN_UR = 0x03;
  88079. return TGATools;
  88080. }());
  88081. BABYLON.TGATools = TGATools;
  88082. })(BABYLON || (BABYLON = {}));
  88083. //# sourceMappingURL=babylon.tga.js.map
  88084. var BABYLON;
  88085. (function (BABYLON) {
  88086. /**
  88087. * Implementation of the TGA Texture Loader.
  88088. */
  88089. var TGATextureLoader = /** @class */ (function () {
  88090. function TGATextureLoader() {
  88091. /**
  88092. * Defines wether the loader supports cascade loading the different faces.
  88093. */
  88094. this.supportCascades = false;
  88095. }
  88096. /**
  88097. * This returns if the loader support the current file information.
  88098. * @param extension defines the file extension of the file being loaded
  88099. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88100. * @param fallback defines the fallback internal texture if any
  88101. * @param isBase64 defines whether the texture is encoded as a base64
  88102. * @param isBuffer defines whether the texture data are stored as a buffer
  88103. * @returns true if the loader can load the specified file
  88104. */
  88105. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88106. return extension.indexOf(".tga") === 0;
  88107. };
  88108. /**
  88109. * Transform the url before loading if required.
  88110. * @param rootUrl the url of the texture
  88111. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88112. * @returns the transformed texture
  88113. */
  88114. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88115. return rootUrl;
  88116. };
  88117. /**
  88118. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88119. * @param rootUrl the url of the texture
  88120. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88121. * @returns the fallback texture
  88122. */
  88123. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88124. return null;
  88125. };
  88126. /**
  88127. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88128. * @param data contains the texture data
  88129. * @param texture defines the BabylonJS internal texture
  88130. * @param createPolynomials will be true if polynomials have been requested
  88131. * @param onLoad defines the callback to trigger once the texture is ready
  88132. * @param onError defines the callback to trigger in case of error
  88133. */
  88134. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88135. throw ".env not supported in Cube.";
  88136. };
  88137. /**
  88138. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88139. * @param data contains the texture data
  88140. * @param texture defines the BabylonJS internal texture
  88141. * @param callback defines the method to call once ready to upload
  88142. */
  88143. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  88144. var uintData = new Uint8Array(data);
  88145. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  88146. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  88147. BABYLON.TGATools.UploadContent(texture, uintData);
  88148. });
  88149. };
  88150. return TGATextureLoader;
  88151. }());
  88152. // Register the loader.
  88153. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  88154. })(BABYLON || (BABYLON = {}));
  88155. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  88156. var BABYLON;
  88157. (function (BABYLON) {
  88158. /**
  88159. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88160. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88161. */
  88162. var KhronosTextureContainer = /** @class */ (function () {
  88163. /**
  88164. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88165. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88166. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88167. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88168. */
  88169. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88170. this.arrayBuffer = arrayBuffer;
  88171. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88172. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88173. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88174. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88175. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88176. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88177. BABYLON.Tools.Error("texture missing KTX identifier");
  88178. return;
  88179. }
  88180. // load the reset of the header in native 32 bit int
  88181. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88182. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88183. var oppositeEndianess = header[0] === 0x01020304;
  88184. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88185. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88186. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88187. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88188. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88189. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88190. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88191. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88192. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88193. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88194. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88195. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88196. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88197. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88198. if (this.glType !== 0) {
  88199. BABYLON.Tools.Error("only compressed formats currently supported");
  88200. return;
  88201. }
  88202. else {
  88203. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88204. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88205. }
  88206. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88207. BABYLON.Tools.Error("only 2D textures currently supported");
  88208. return;
  88209. }
  88210. if (this.numberOfArrayElements !== 0) {
  88211. BABYLON.Tools.Error("texture arrays not currently supported");
  88212. return;
  88213. }
  88214. if (this.numberOfFaces !== facesExpected) {
  88215. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88216. return;
  88217. }
  88218. // we now have a completely validated file, so could use existence of loadType as success
  88219. // would need to make this more elaborate & adjust checks above to support more than one load type
  88220. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88221. }
  88222. // not as fast hardware based, but will probably never need to use
  88223. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88224. return ((val & 0xFF) << 24)
  88225. | ((val & 0xFF00) << 8)
  88226. | ((val >> 8) & 0xFF00)
  88227. | ((val >> 24) & 0xFF);
  88228. };
  88229. /**
  88230. * Uploads KTX content to a Babylon Texture.
  88231. * It is assumed that the texture has already been created & is currently bound
  88232. * @hidden
  88233. */
  88234. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  88235. switch (this.loadType) {
  88236. case KhronosTextureContainer.COMPRESSED_2D:
  88237. this._upload2DCompressedLevels(texture, loadMipmaps);
  88238. break;
  88239. case KhronosTextureContainer.TEX_2D:
  88240. case KhronosTextureContainer.COMPRESSED_3D:
  88241. case KhronosTextureContainer.TEX_3D:
  88242. }
  88243. };
  88244. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  88245. // initialize width & height for level 1
  88246. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  88247. var width = this.pixelWidth;
  88248. var height = this.pixelHeight;
  88249. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  88250. for (var level = 0; level < mipmapCount; level++) {
  88251. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  88252. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  88253. for (var face = 0; face < this.numberOfFaces; face++) {
  88254. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  88255. var engine = texture.getEngine();
  88256. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  88257. dataOffset += imageSize; // add size of the image for the next face/mipmap
  88258. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  88259. }
  88260. width = Math.max(1.0, width * 0.5);
  88261. height = Math.max(1.0, height * 0.5);
  88262. }
  88263. };
  88264. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  88265. // load types
  88266. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  88267. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  88268. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  88269. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  88270. return KhronosTextureContainer;
  88271. }());
  88272. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  88273. })(BABYLON || (BABYLON = {}));
  88274. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  88275. var BABYLON;
  88276. (function (BABYLON) {
  88277. /**
  88278. * Implementation of the KTX Texture Loader.
  88279. */
  88280. var KTXTextureLoader = /** @class */ (function () {
  88281. function KTXTextureLoader() {
  88282. /**
  88283. * Defines wether the loader supports cascade loading the different faces.
  88284. */
  88285. this.supportCascades = false;
  88286. }
  88287. /**
  88288. * This returns if the loader support the current file information.
  88289. * @param extension defines the file extension of the file being loaded
  88290. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88291. * @param fallback defines the fallback internal texture if any
  88292. * @param isBase64 defines whether the texture is encoded as a base64
  88293. * @param isBuffer defines whether the texture data are stored as a buffer
  88294. * @returns true if the loader can load the specified file
  88295. */
  88296. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88297. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  88298. return true;
  88299. }
  88300. return false;
  88301. };
  88302. /**
  88303. * Transform the url before loading if required.
  88304. * @param rootUrl the url of the texture
  88305. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88306. * @returns the transformed texture
  88307. */
  88308. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88309. var lastDot = rootUrl.lastIndexOf('.');
  88310. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  88311. };
  88312. /**
  88313. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88314. * @param rootUrl the url of the texture
  88315. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88316. * @returns the fallback texture
  88317. */
  88318. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88319. // remove the format appended to the rootUrl in the original createCubeTexture call.
  88320. var exp = new RegExp("" + textureFormatInUse + "$");
  88321. return rootUrl.replace(exp, "");
  88322. };
  88323. /**
  88324. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88325. * @param data contains the texture data
  88326. * @param texture defines the BabylonJS internal texture
  88327. * @param createPolynomials will be true if polynomials have been requested
  88328. * @param onLoad defines the callback to trigger once the texture is ready
  88329. * @param onError defines the callback to trigger in case of error
  88330. */
  88331. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88332. if (Array.isArray(data)) {
  88333. return;
  88334. }
  88335. var engine = texture.getEngine();
  88336. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  88337. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  88338. engine._unpackFlipY(true);
  88339. ktx.uploadLevels(texture, texture.generateMipMaps);
  88340. texture.width = ktx.pixelWidth;
  88341. texture.height = ktx.pixelHeight;
  88342. engine._setCubeMapTextureParams(loadMipmap);
  88343. texture.isReady = true;
  88344. };
  88345. /**
  88346. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88347. * @param data contains the texture data
  88348. * @param texture defines the BabylonJS internal texture
  88349. * @param callback defines the method to call once ready to upload
  88350. */
  88351. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  88352. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  88353. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  88354. ktx.uploadLevels(texture, texture.generateMipMaps);
  88355. });
  88356. };
  88357. return KTXTextureLoader;
  88358. }());
  88359. // Register the loader.
  88360. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  88361. })(BABYLON || (BABYLON = {}));
  88362. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  88363. var BABYLON;
  88364. (function (BABYLON) {
  88365. /**
  88366. * Sets of helpers addressing the serialization and deserialization of environment texture
  88367. * stored in a BabylonJS env file.
  88368. * Those files are usually stored as .env files.
  88369. */
  88370. var EnvironmentTextureTools = /** @class */ (function () {
  88371. function EnvironmentTextureTools() {
  88372. }
  88373. /**
  88374. * Gets the environment info from an env file.
  88375. * @param data The array buffer containing the .env bytes.
  88376. * @returns the environment file info (the json header) if successfully parsed.
  88377. */
  88378. EnvironmentTextureTools.GetEnvInfo = function (data) {
  88379. var dataView = new DataView(data);
  88380. var pos = 0;
  88381. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88382. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  88383. BABYLON.Tools.Error('Not a babylon environment map');
  88384. return null;
  88385. }
  88386. }
  88387. // Read json manifest - collect characters up to null terminator
  88388. var manifestString = '';
  88389. var charCode = 0x00;
  88390. while ((charCode = dataView.getUint8(pos++))) {
  88391. manifestString += String.fromCharCode(charCode);
  88392. }
  88393. var manifest = JSON.parse(manifestString);
  88394. if (manifest.specular) {
  88395. // Extend the header with the position of the payload.
  88396. manifest.specular.specularDataPosition = pos;
  88397. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  88398. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  88399. }
  88400. return manifest;
  88401. };
  88402. /**
  88403. * Creates an environment texture from a loaded cube texture.
  88404. * @param texture defines the cube texture to convert in env file
  88405. * @return a promise containing the environment data if succesfull.
  88406. */
  88407. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  88408. var _this = this;
  88409. var internalTexture = texture.getInternalTexture();
  88410. if (!internalTexture) {
  88411. return Promise.reject("The cube texture is invalid.");
  88412. }
  88413. if (!texture._prefiltered) {
  88414. return Promise.reject("The cube texture is invalid (not prefiltered).");
  88415. }
  88416. var engine = internalTexture.getEngine();
  88417. if (engine && engine.premultipliedAlpha) {
  88418. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  88419. }
  88420. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  88421. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  88422. }
  88423. var canvas = engine.getRenderingCanvas();
  88424. if (!canvas) {
  88425. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  88426. }
  88427. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88428. if (!engine.getCaps().textureFloatRender) {
  88429. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88430. if (!engine.getCaps().textureHalfFloatRender) {
  88431. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  88432. }
  88433. }
  88434. var cubeWidth = internalTexture.width;
  88435. var hostingScene = new BABYLON.Scene(engine);
  88436. var specularTextures = {};
  88437. var promises = [];
  88438. // Read and collect all mipmaps data from the cube.
  88439. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  88440. mipmapsCount = Math.round(mipmapsCount);
  88441. var _loop_1 = function (i) {
  88442. var faceWidth = Math.pow(2, mipmapsCount - i);
  88443. var _loop_2 = function (face) {
  88444. var data = texture.readPixels(face, i);
  88445. // Creates a temp texture with the face data.
  88446. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  88447. // And rgbdEncode them.
  88448. var promise = new Promise(function (resolve, reject) {
  88449. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  88450. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88451. rgbdPostProcess.onApply = function (effect) {
  88452. effect._bindTexture("textureSampler", tempTexture);
  88453. };
  88454. // As the process needs to happen on the main canvas, keep track of the current size
  88455. var currentW = engine.getRenderWidth();
  88456. var currentH = engine.getRenderHeight();
  88457. // Set the desired size for the texture
  88458. engine.setSize(faceWidth, faceWidth);
  88459. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  88460. // Reading datas from WebGL
  88461. BABYLON.Tools.ToBlob(canvas, function (blob) {
  88462. var fileReader = new FileReader();
  88463. fileReader.onload = function (event) {
  88464. var arrayBuffer = event.target.result;
  88465. specularTextures[i * 6 + face] = arrayBuffer;
  88466. resolve();
  88467. };
  88468. fileReader.readAsArrayBuffer(blob);
  88469. });
  88470. // Reapply the previous canvas size
  88471. engine.setSize(currentW, currentH);
  88472. });
  88473. });
  88474. promises.push(promise);
  88475. };
  88476. // All faces of the cube.
  88477. for (var face = 0; face < 6; face++) {
  88478. _loop_2(face);
  88479. }
  88480. };
  88481. for (var i = 0; i <= mipmapsCount; i++) {
  88482. _loop_1(i);
  88483. }
  88484. // Once all the textures haves been collected as RGBD stored in PNGs
  88485. return Promise.all(promises).then(function () {
  88486. // We can delete the hosting scene keeping track of all the creation objects
  88487. hostingScene.dispose();
  88488. // Creates the json header for the env texture
  88489. var info = {
  88490. version: 1,
  88491. width: cubeWidth,
  88492. irradiance: _this._CreateEnvTextureIrradiance(texture),
  88493. specular: {
  88494. mipmaps: [],
  88495. lodGenerationScale: texture.lodGenerationScale
  88496. }
  88497. };
  88498. // Sets the specular image data information
  88499. var position = 0;
  88500. for (var i = 0; i <= mipmapsCount; i++) {
  88501. for (var face = 0; face < 6; face++) {
  88502. var byteLength = specularTextures[i * 6 + face].byteLength;
  88503. info.specular.mipmaps.push({
  88504. length: byteLength,
  88505. position: position
  88506. });
  88507. position += byteLength;
  88508. }
  88509. }
  88510. // Encode the JSON as an array buffer
  88511. var infoString = JSON.stringify(info);
  88512. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  88513. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  88514. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  88515. infoView[i] = infoString.charCodeAt(i);
  88516. }
  88517. // Ends up with a null terminator for easier parsing
  88518. infoView[infoString.length] = 0x00;
  88519. // Computes the final required size and creates the storage
  88520. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  88521. var finalBuffer = new ArrayBuffer(totalSize);
  88522. var finalBufferView = new Uint8Array(finalBuffer);
  88523. var dataView = new DataView(finalBuffer);
  88524. // Copy the magic bytes identifying the file in
  88525. var pos = 0;
  88526. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88527. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  88528. }
  88529. // Add the json info
  88530. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  88531. pos += infoBuffer.byteLength;
  88532. // Finally inserts the texture data
  88533. for (var i = 0; i <= mipmapsCount; i++) {
  88534. for (var face = 0; face < 6; face++) {
  88535. var dataBuffer = specularTextures[i * 6 + face];
  88536. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  88537. pos += dataBuffer.byteLength;
  88538. }
  88539. }
  88540. // Voila
  88541. return finalBuffer;
  88542. });
  88543. };
  88544. /**
  88545. * Creates a JSON representation of the spherical data.
  88546. * @param texture defines the texture containing the polynomials
  88547. * @return the JSON representation of the spherical info
  88548. */
  88549. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  88550. var polynmials = texture.sphericalPolynomial;
  88551. if (polynmials == null) {
  88552. return null;
  88553. }
  88554. return {
  88555. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  88556. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  88557. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  88558. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  88559. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  88560. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  88561. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  88562. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  88563. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  88564. };
  88565. };
  88566. /**
  88567. * Uploads the texture info contained in the env file to the GPU.
  88568. * @param texture defines the internal texture to upload to
  88569. * @param arrayBuffer defines the buffer cotaining the data to load
  88570. * @param info defines the texture info retrieved through the GetEnvInfo method
  88571. * @returns a promise
  88572. */
  88573. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  88574. if (info.version !== 1) {
  88575. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  88576. }
  88577. var specularInfo = info.specular;
  88578. if (!specularInfo) {
  88579. // Nothing else parsed so far
  88580. return Promise.resolve();
  88581. }
  88582. // Double checks the enclosed info
  88583. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  88584. mipmapsCount = Math.round(mipmapsCount) + 1;
  88585. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  88586. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  88587. }
  88588. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  88589. var imageData = new Array(mipmapsCount);
  88590. for (var i = 0; i < mipmapsCount; i++) {
  88591. imageData[i] = new Array(6);
  88592. for (var face = 0; face < 6; face++) {
  88593. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  88594. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  88595. }
  88596. }
  88597. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  88598. };
  88599. /**
  88600. * Uploads the levels of image data to the GPU.
  88601. * @param texture defines the internal texture to upload to
  88602. * @param imageData defines the array buffer views of image data [mipmap][face]
  88603. * @returns a promise
  88604. */
  88605. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  88606. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  88607. throw new Error("Texture size must be a power of two");
  88608. }
  88609. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  88610. // Gets everything ready.
  88611. var engine = texture.getEngine();
  88612. var expandTexture = false;
  88613. var generateNonLODTextures = false;
  88614. var rgbdPostProcess = null;
  88615. var cubeRtt = null;
  88616. var lodTextures = null;
  88617. var caps = engine.getCaps();
  88618. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88619. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88620. texture.generateMipMaps = true;
  88621. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  88622. // Add extra process if texture lod is not supported
  88623. if (!caps.textureLOD) {
  88624. expandTexture = false;
  88625. generateNonLODTextures = true;
  88626. lodTextures = {};
  88627. }
  88628. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  88629. else if (engine.webGLVersion < 2) {
  88630. expandTexture = false;
  88631. }
  88632. // If half float available we can uncompress the texture
  88633. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  88634. expandTexture = true;
  88635. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88636. }
  88637. // If full float available we can uncompress the texture
  88638. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  88639. expandTexture = true;
  88640. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88641. }
  88642. // Expand the texture if possible
  88643. if (expandTexture) {
  88644. // Simply run through the decode PP
  88645. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  88646. texture._isRGBD = false;
  88647. texture.invertY = false;
  88648. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  88649. generateDepthBuffer: false,
  88650. generateMipMaps: true,
  88651. generateStencilBuffer: false,
  88652. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  88653. type: texture.type,
  88654. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  88655. });
  88656. }
  88657. else {
  88658. texture._isRGBD = true;
  88659. texture.invertY = true;
  88660. // In case of missing support, applies the same patch than DDS files.
  88661. if (generateNonLODTextures) {
  88662. var mipSlices = 3;
  88663. var scale = texture._lodGenerationScale;
  88664. var offset = texture._lodGenerationOffset;
  88665. for (var i = 0; i < mipSlices; i++) {
  88666. //compute LOD from even spacing in smoothness (matching shader calculation)
  88667. var smoothness = i / (mipSlices - 1);
  88668. var roughness = 1 - smoothness;
  88669. var minLODIndex = offset; // roughness = 0
  88670. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  88671. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  88672. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  88673. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  88674. glTextureFromLod.isCube = true;
  88675. glTextureFromLod.invertY = true;
  88676. glTextureFromLod.generateMipMaps = false;
  88677. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  88678. // Wrap in a base texture for easy binding.
  88679. var lodTexture = new BABYLON.BaseTexture(null);
  88680. lodTexture.isCube = true;
  88681. lodTexture._texture = glTextureFromLod;
  88682. lodTextures[mipmapIndex] = lodTexture;
  88683. switch (i) {
  88684. case 0:
  88685. texture._lodTextureLow = lodTexture;
  88686. break;
  88687. case 1:
  88688. texture._lodTextureMid = lodTexture;
  88689. break;
  88690. case 2:
  88691. texture._lodTextureHigh = lodTexture;
  88692. break;
  88693. }
  88694. }
  88695. }
  88696. }
  88697. var promises = [];
  88698. var _loop_3 = function (i) {
  88699. var _loop_4 = function (face) {
  88700. // Constructs an image element from image data
  88701. var bytes = imageData[i][face];
  88702. var blob = new Blob([bytes], { type: 'image/png' });
  88703. var url = URL.createObjectURL(blob);
  88704. var image = new Image();
  88705. image.src = url;
  88706. // Enqueue promise to upload to the texture.
  88707. var promise = new Promise(function (resolve, reject) {
  88708. image.onload = function () {
  88709. if (expandTexture) {
  88710. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  88711. reject(message);
  88712. }, image);
  88713. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88714. // Uncompress the data to a RTT
  88715. rgbdPostProcess.onApply = function (effect) {
  88716. effect._bindTexture("textureSampler", tempTexture_1);
  88717. effect.setFloat2("scale", 1, 1);
  88718. };
  88719. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  88720. // Cleanup
  88721. engine.restoreDefaultFramebuffer();
  88722. tempTexture_1.dispose();
  88723. window.URL.revokeObjectURL(url);
  88724. resolve();
  88725. });
  88726. }
  88727. else {
  88728. engine._uploadImageToTexture(texture, image, face, i);
  88729. // Upload the face to the non lod texture support
  88730. if (generateNonLODTextures) {
  88731. var lodTexture = lodTextures[i];
  88732. if (lodTexture) {
  88733. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  88734. }
  88735. }
  88736. resolve();
  88737. }
  88738. };
  88739. image.onerror = function (error) {
  88740. reject(error);
  88741. };
  88742. });
  88743. promises.push(promise);
  88744. };
  88745. // All faces
  88746. for (var face = 0; face < 6; face++) {
  88747. _loop_4(face);
  88748. }
  88749. };
  88750. // All mipmaps up to provided number of images
  88751. for (var i = 0; i < imageData.length; i++) {
  88752. _loop_3(i);
  88753. }
  88754. // Fill remaining mipmaps with black textures.
  88755. if (imageData.length < mipmapsCount) {
  88756. var data = void 0;
  88757. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  88758. var dataLength = size * size * 4;
  88759. switch (texture.type) {
  88760. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  88761. data = new Uint8Array(dataLength);
  88762. break;
  88763. }
  88764. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  88765. data = new Uint16Array(dataLength);
  88766. break;
  88767. }
  88768. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  88769. data = new Float32Array(dataLength);
  88770. break;
  88771. }
  88772. }
  88773. for (var i = imageData.length; i < mipmapsCount; i++) {
  88774. for (var face = 0; face < 6; face++) {
  88775. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  88776. }
  88777. }
  88778. }
  88779. // Once all done, finishes the cleanup and return
  88780. return Promise.all(promises).then(function () {
  88781. // Release temp RTT.
  88782. if (cubeRtt) {
  88783. engine._releaseFramebufferObjects(cubeRtt);
  88784. cubeRtt._swapAndDie(texture);
  88785. }
  88786. // Release temp Post Process.
  88787. if (rgbdPostProcess) {
  88788. rgbdPostProcess.dispose();
  88789. }
  88790. // Flag internal texture as ready in case they are in use.
  88791. if (generateNonLODTextures) {
  88792. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  88793. texture._lodTextureHigh._texture.isReady = true;
  88794. }
  88795. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  88796. texture._lodTextureMid._texture.isReady = true;
  88797. }
  88798. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  88799. texture._lodTextureLow._texture.isReady = true;
  88800. }
  88801. }
  88802. });
  88803. };
  88804. /**
  88805. * Uploads spherical polynomials information to the texture.
  88806. * @param texture defines the texture we are trying to upload the information to
  88807. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  88808. */
  88809. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  88810. if (info.version !== 1) {
  88811. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  88812. }
  88813. var irradianceInfo = info.irradiance;
  88814. if (!irradianceInfo) {
  88815. return;
  88816. }
  88817. var sp = new BABYLON.SphericalPolynomial();
  88818. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  88819. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  88820. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  88821. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  88822. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  88823. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  88824. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  88825. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  88826. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  88827. texture._sphericalPolynomial = sp;
  88828. };
  88829. /**
  88830. * Magic number identifying the env file.
  88831. */
  88832. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  88833. return EnvironmentTextureTools;
  88834. }());
  88835. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  88836. })(BABYLON || (BABYLON = {}));
  88837. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  88838. var BABYLON;
  88839. (function (BABYLON) {
  88840. /**
  88841. * Implementation of the ENV Texture Loader.
  88842. */
  88843. var ENVTextureLoader = /** @class */ (function () {
  88844. function ENVTextureLoader() {
  88845. /**
  88846. * Defines wether the loader supports cascade loading the different faces.
  88847. */
  88848. this.supportCascades = false;
  88849. }
  88850. /**
  88851. * This returns if the loader support the current file information.
  88852. * @param extension defines the file extension of the file being loaded
  88853. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88854. * @param fallback defines the fallback internal texture if any
  88855. * @param isBase64 defines whether the texture is encoded as a base64
  88856. * @param isBuffer defines whether the texture data are stored as a buffer
  88857. * @returns true if the loader can load the specified file
  88858. */
  88859. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88860. return extension.indexOf(".env") === 0;
  88861. };
  88862. /**
  88863. * Transform the url before loading if required.
  88864. * @param rootUrl the url of the texture
  88865. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88866. * @returns the transformed texture
  88867. */
  88868. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88869. return rootUrl;
  88870. };
  88871. /**
  88872. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88873. * @param rootUrl the url of the texture
  88874. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88875. * @returns the fallback texture
  88876. */
  88877. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88878. return null;
  88879. };
  88880. /**
  88881. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88882. * @param data contains the texture data
  88883. * @param texture defines the BabylonJS internal texture
  88884. * @param createPolynomials will be true if polynomials have been requested
  88885. * @param onLoad defines the callback to trigger once the texture is ready
  88886. * @param onError defines the callback to trigger in case of error
  88887. */
  88888. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88889. if (Array.isArray(data)) {
  88890. return;
  88891. }
  88892. data = data;
  88893. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  88894. if (info) {
  88895. texture.width = info.width;
  88896. texture.height = info.width;
  88897. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  88898. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  88899. texture.isReady = true;
  88900. if (onLoad) {
  88901. onLoad();
  88902. }
  88903. });
  88904. }
  88905. else if (onError) {
  88906. onError("Can not parse the environment file", null);
  88907. }
  88908. };
  88909. /**
  88910. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88911. * @param data contains the texture data
  88912. * @param texture defines the BabylonJS internal texture
  88913. * @param callback defines the method to call once ready to upload
  88914. */
  88915. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  88916. throw ".env not supported in 2d.";
  88917. };
  88918. return ENVTextureLoader;
  88919. }());
  88920. // Register the loader.
  88921. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  88922. })(BABYLON || (BABYLON = {}));
  88923. //# sourceMappingURL=babylon.envTextureLoader.js.map
  88924. var BABYLON;
  88925. (function (BABYLON) {
  88926. /**
  88927. * Renders a layer on top of an existing scene
  88928. */
  88929. var UtilityLayerRenderer = /** @class */ (function () {
  88930. /**
  88931. * Instantiates a UtilityLayerRenderer
  88932. * @param originalScene the original scene that will be rendered on top of
  88933. */
  88934. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88935. var _this = this;
  88936. this.originalScene = originalScene;
  88937. this._pointerCaptures = {};
  88938. this._lastPointerEvents = {};
  88939. /**
  88940. * If the utility layer should automatically be rendered on top of existing scene
  88941. */
  88942. this.shouldRender = true;
  88943. /**
  88944. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88945. */
  88946. this.onlyCheckPointerDownEvents = true;
  88947. /**
  88948. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88949. */
  88950. this.processAllEvents = false;
  88951. /**
  88952. * Observable raised when the pointer move from the utility layer scene to the main scene
  88953. */
  88954. this.onPointerOutObservable = new BABYLON.Observable();
  88955. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88956. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88957. this.utilityLayerScene._allowPostProcessClear = false;
  88958. originalScene.getEngine().scenes.pop();
  88959. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88960. this.utilityLayerScene.detachControl();
  88961. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88962. if (!_this.processAllEvents) {
  88963. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88964. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88965. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88966. return;
  88967. }
  88968. }
  88969. var pointerEvent = (prePointerInfo.event);
  88970. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88971. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88972. return;
  88973. }
  88974. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88975. if (!prePointerInfo.ray && utilityScenePick) {
  88976. prePointerInfo.ray = utilityScenePick.ray;
  88977. }
  88978. // always fire the prepointer oversvable
  88979. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88980. // allow every non pointer down event to flow to the utility layer
  88981. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88982. if (!prePointerInfo.skipOnPointerObservable) {
  88983. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88984. }
  88985. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88986. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88987. }
  88988. return;
  88989. }
  88990. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88991. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88992. if (utilityScenePick && utilityScenePick.hit) {
  88993. if (!prePointerInfo.skipOnPointerObservable) {
  88994. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88995. }
  88996. prePointerInfo.skipOnPointerObservable = true;
  88997. }
  88998. }
  88999. else {
  89000. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  89001. var pointerEvent_1 = (prePointerInfo.event);
  89002. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  89003. if (originalScenePick && utilityScenePick) {
  89004. // No pick in utility scene
  89005. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  89006. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89007. // We touched an utility mesh present in the main scene
  89008. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89009. prePointerInfo.skipOnPointerObservable = true;
  89010. }
  89011. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89012. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  89013. }
  89014. }
  89015. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  89016. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  89017. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  89018. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  89019. }
  89020. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  89021. // We have a pick in both scenes but main is closer than utility
  89022. // We touched an utility mesh present in the main scene
  89023. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89024. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89025. prePointerInfo.skipOnPointerObservable = true;
  89026. }
  89027. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  89028. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  89029. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  89030. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  89031. }
  89032. }
  89033. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  89034. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  89035. }
  89036. }
  89037. }
  89038. });
  89039. // Render directly on top of existing scene without clearing
  89040. this.utilityLayerScene.autoClear = false;
  89041. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  89042. if (_this.shouldRender) {
  89043. _this.render();
  89044. }
  89045. });
  89046. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  89047. _this.dispose();
  89048. });
  89049. this._updateCamera();
  89050. }
  89051. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  89052. /**
  89053. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  89054. */
  89055. get: function () {
  89056. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  89057. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89058. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89059. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89060. });
  89061. }
  89062. return UtilityLayerRenderer._DefaultUtilityLayer;
  89063. },
  89064. enumerable: true,
  89065. configurable: true
  89066. });
  89067. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  89068. /**
  89069. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  89070. */
  89071. get: function () {
  89072. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  89073. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89074. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  89075. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89076. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89077. });
  89078. }
  89079. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  89080. },
  89081. enumerable: true,
  89082. configurable: true
  89083. });
  89084. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  89085. if (!prePointerInfo.skipOnPointerObservable) {
  89086. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  89087. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  89088. }
  89089. };
  89090. /**
  89091. * Renders the utility layers scene on top of the original scene
  89092. */
  89093. UtilityLayerRenderer.prototype.render = function () {
  89094. this._updateCamera();
  89095. if (this.utilityLayerScene.activeCamera) {
  89096. // Set the camera's scene to utility layers scene
  89097. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  89098. var camera = this.utilityLayerScene.activeCamera;
  89099. camera._scene = this.utilityLayerScene;
  89100. if (camera.leftCamera) {
  89101. camera.leftCamera._scene = this.utilityLayerScene;
  89102. }
  89103. if (camera.rightCamera) {
  89104. camera.rightCamera._scene = this.utilityLayerScene;
  89105. }
  89106. this.utilityLayerScene.render(false);
  89107. // Reset camera's scene back to original
  89108. camera._scene = oldScene;
  89109. if (camera.leftCamera) {
  89110. camera.leftCamera._scene = oldScene;
  89111. }
  89112. if (camera.rightCamera) {
  89113. camera.rightCamera._scene = oldScene;
  89114. }
  89115. }
  89116. };
  89117. /**
  89118. * Disposes of the renderer
  89119. */
  89120. UtilityLayerRenderer.prototype.dispose = function () {
  89121. this.onPointerOutObservable.clear();
  89122. if (this._afterRenderObserver) {
  89123. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  89124. }
  89125. if (this._sceneDisposeObserver) {
  89126. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89127. }
  89128. if (this._originalPointerObserver) {
  89129. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  89130. }
  89131. this.utilityLayerScene.dispose();
  89132. };
  89133. UtilityLayerRenderer.prototype._updateCamera = function () {
  89134. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  89135. };
  89136. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89137. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89138. return UtilityLayerRenderer;
  89139. }());
  89140. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  89141. })(BABYLON || (BABYLON = {}));
  89142. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  89143. //# sourceMappingURL=babylon.behavior.js.map
  89144. var BABYLON;
  89145. (function (BABYLON) {
  89146. /**
  89147. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  89148. */
  89149. var PointerDragBehavior = /** @class */ (function () {
  89150. /**
  89151. * Creates a pointer drag behavior that can be attached to a mesh
  89152. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  89153. */
  89154. function PointerDragBehavior(options) {
  89155. /**
  89156. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  89157. */
  89158. this.maxDragAngle = 0;
  89159. /**
  89160. * @hidden
  89161. */
  89162. this._useAlternatePickedPointAboveMaxDragAngle = false;
  89163. /**
  89164. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89165. */
  89166. this.currentDraggingPointerID = -1;
  89167. /**
  89168. * If the behavior is currently in a dragging state
  89169. */
  89170. this.dragging = false;
  89171. /**
  89172. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89173. */
  89174. this.dragDeltaRatio = 0.2;
  89175. /**
  89176. * If the drag plane orientation should be updated during the dragging (Default: true)
  89177. */
  89178. this.updateDragPlane = true;
  89179. // Debug mode will display drag planes to help visualize behavior
  89180. this._debugMode = false;
  89181. this._moving = false;
  89182. /**
  89183. * Fires each time the attached mesh is dragged with the pointer
  89184. * * delta between last drag position and current drag position in world space
  89185. * * dragDistance along the drag axis
  89186. * * dragPlaneNormal normal of the current drag plane used during the drag
  89187. * * dragPlanePoint in world space where the drag intersects the drag plane
  89188. */
  89189. this.onDragObservable = new BABYLON.Observable();
  89190. /**
  89191. * Fires each time a drag begins (eg. mouse down on mesh)
  89192. */
  89193. this.onDragStartObservable = new BABYLON.Observable();
  89194. /**
  89195. * Fires each time a drag ends (eg. mouse release after drag)
  89196. */
  89197. this.onDragEndObservable = new BABYLON.Observable();
  89198. /**
  89199. * If the attached mesh should be moved when dragged
  89200. */
  89201. this.moveAttached = true;
  89202. /**
  89203. * If the drag behavior will react to drag events (Default: true)
  89204. */
  89205. this.enabled = true;
  89206. /**
  89207. * If camera controls should be detached during the drag
  89208. */
  89209. this.detachCameraControls = true;
  89210. /**
  89211. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  89212. */
  89213. this.useObjectOrienationForDragging = true;
  89214. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89215. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  89216. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  89217. // Variables to avoid instantiation in the below method
  89218. this._pointA = new BABYLON.Vector3(0, 0, 0);
  89219. this._pointB = new BABYLON.Vector3(0, 0, 0);
  89220. this._pointC = new BABYLON.Vector3(0, 0, 0);
  89221. this._lineA = new BABYLON.Vector3(0, 0, 0);
  89222. this._lineB = new BABYLON.Vector3(0, 0, 0);
  89223. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  89224. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  89225. this._options = options ? options : {};
  89226. var optionCount = 0;
  89227. if (this._options.dragAxis) {
  89228. optionCount++;
  89229. }
  89230. if (this._options.dragPlaneNormal) {
  89231. optionCount++;
  89232. }
  89233. if (optionCount > 1) {
  89234. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  89235. }
  89236. }
  89237. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  89238. /**
  89239. * The name of the behavior
  89240. */
  89241. get: function () {
  89242. return "PointerDrag";
  89243. },
  89244. enumerable: true,
  89245. configurable: true
  89246. });
  89247. /**
  89248. * Initializes the behavior
  89249. */
  89250. PointerDragBehavior.prototype.init = function () { };
  89251. /**
  89252. * Attaches the drag behavior the passed in mesh
  89253. * @param ownerNode The mesh that will be dragged around once attached
  89254. */
  89255. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89256. var _this = this;
  89257. this._scene = ownerNode.getScene();
  89258. this._attachedNode = ownerNode;
  89259. // Initialize drag plane to not interfere with existing scene
  89260. if (!PointerDragBehavior._planeScene) {
  89261. if (this._debugMode) {
  89262. PointerDragBehavior._planeScene = this._scene;
  89263. }
  89264. else {
  89265. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89266. PointerDragBehavior._planeScene.detachControl();
  89267. this._scene.getEngine().scenes.pop();
  89268. this._scene.onDisposeObservable.addOnce(function () {
  89269. PointerDragBehavior._planeScene.dispose();
  89270. PointerDragBehavior._planeScene = null;
  89271. });
  89272. }
  89273. }
  89274. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89275. // State of the drag
  89276. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89277. var delta = new BABYLON.Vector3(0, 0, 0);
  89278. var dragLength = 0;
  89279. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89280. var pickPredicate = function (m) {
  89281. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89282. };
  89283. var attachedElement = null;
  89284. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89285. if (!_this.enabled) {
  89286. return;
  89287. }
  89288. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89289. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89290. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89291. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89292. if (pickedPoint) {
  89293. _this.dragging = true;
  89294. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89295. _this.lastDragPosition.copyFrom(pickedPoint);
  89296. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89297. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89298. // Detatch camera controls
  89299. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89300. if (_this._scene.activeCamera.inputs.attachedElement) {
  89301. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89302. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89303. }
  89304. else {
  89305. attachedElement = null;
  89306. }
  89307. }
  89308. }
  89309. }
  89310. }
  89311. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89312. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89313. _this.releaseDrag();
  89314. // Reattach camera controls
  89315. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89316. _this._scene.activeCamera.attachControl(attachedElement, true);
  89317. }
  89318. }
  89319. }
  89320. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89321. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89322. _this._moving = true;
  89323. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89324. if (pickedPoint) {
  89325. if (_this.updateDragPlane) {
  89326. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89327. }
  89328. // depending on the drag mode option drag accordingly
  89329. if (_this._options.dragAxis) {
  89330. // Convert local drag axis to world
  89331. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89332. // Project delta drag from the drag plane onto the drag axis
  89333. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89334. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89335. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89336. }
  89337. else {
  89338. dragLength = delta.length();
  89339. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89340. }
  89341. targetPosition.addInPlace(delta);
  89342. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89343. _this.lastDragPosition.copyFrom(pickedPoint);
  89344. }
  89345. }
  89346. }
  89347. });
  89348. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89349. if (_this._moving && _this.moveAttached) {
  89350. // Slowly move mesh to avoid jitter
  89351. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89352. _this._tmpVector.scaleInPlace(0.2);
  89353. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89354. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89355. }
  89356. });
  89357. };
  89358. PointerDragBehavior.prototype.releaseDrag = function () {
  89359. this.dragging = false;
  89360. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89361. this.currentDraggingPointerID = -1;
  89362. this._moving = false;
  89363. };
  89364. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89365. var _this = this;
  89366. if (!ray) {
  89367. return null;
  89368. }
  89369. // Calculate angle between plane normal and ray
  89370. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89371. // Correct if ray is casted from oposite side
  89372. if (angle > Math.PI / 2) {
  89373. angle = Math.PI - angle;
  89374. }
  89375. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89376. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89377. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89378. // Invert ray direction along the towards object axis
  89379. this._tmpVector.copyFrom(ray.direction);
  89380. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89381. this._alternatePickedPoint.normalize();
  89382. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89383. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89384. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89385. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89386. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89387. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89388. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89389. return this._alternatePickedPoint;
  89390. }
  89391. else {
  89392. return null;
  89393. }
  89394. }
  89395. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89396. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89397. return pickResult.pickedPoint;
  89398. }
  89399. else {
  89400. return null;
  89401. }
  89402. };
  89403. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89404. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89405. this._pointA.copyFrom(dragPlanePosition);
  89406. if (this._options.dragAxis) {
  89407. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  89408. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89409. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89410. ray.origin.subtractToRef(this._pointA, this._pointC);
  89411. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89412. // Get perpendicular line from direction to camera and drag axis
  89413. this._pointB.subtractToRef(this._pointA, this._lineA);
  89414. this._pointC.subtractToRef(this._pointA, this._lineB);
  89415. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89416. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89417. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89418. this._lookAt.normalize();
  89419. this._dragPlane.position.copyFrom(this._pointA);
  89420. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89421. this._dragPlane.lookAt(this._lookAt);
  89422. }
  89423. else if (this._options.dragPlaneNormal) {
  89424. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  89425. this._dragPlane.position.copyFrom(this._pointA);
  89426. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89427. this._dragPlane.lookAt(this._lookAt);
  89428. }
  89429. else {
  89430. this._dragPlane.position.copyFrom(this._pointA);
  89431. this._dragPlane.lookAt(ray.origin);
  89432. }
  89433. this._dragPlane.computeWorldMatrix(true);
  89434. };
  89435. /**
  89436. * Detaches the behavior from the mesh
  89437. */
  89438. PointerDragBehavior.prototype.detach = function () {
  89439. if (this._pointerObserver) {
  89440. this._scene.onPointerObservable.remove(this._pointerObserver);
  89441. }
  89442. if (this._beforeRenderObserver) {
  89443. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89444. }
  89445. };
  89446. return PointerDragBehavior;
  89447. }());
  89448. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89449. })(BABYLON || (BABYLON = {}));
  89450. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89451. var BABYLON;
  89452. (function (BABYLON) {
  89453. /**
  89454. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89455. */
  89456. var MultiPointerScaleBehavior = /** @class */ (function () {
  89457. function MultiPointerScaleBehavior() {
  89458. this._startDistance = 0;
  89459. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89460. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89461. this._sceneRenderObserver = null;
  89462. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89463. this._dragBehaviorA.moveAttached = false;
  89464. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89465. this._dragBehaviorB.moveAttached = false;
  89466. }
  89467. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89468. /**
  89469. * The name of the behavior
  89470. */
  89471. get: function () {
  89472. return "MultiPointerScale";
  89473. },
  89474. enumerable: true,
  89475. configurable: true
  89476. });
  89477. /**
  89478. * Initializes the behavior
  89479. */
  89480. MultiPointerScaleBehavior.prototype.init = function () { };
  89481. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89482. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89483. };
  89484. /**
  89485. * Attaches the scale behavior the passed in mesh
  89486. * @param ownerNode The mesh that will be scaled around once attached
  89487. */
  89488. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89489. var _this = this;
  89490. this._ownerNode = ownerNode;
  89491. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89492. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89493. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89494. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89495. _this._dragBehaviorA.releaseDrag();
  89496. }
  89497. else {
  89498. _this._initialScale.copyFrom(ownerNode.scaling);
  89499. _this._startDistance = _this._getCurrentDistance();
  89500. }
  89501. }
  89502. });
  89503. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89504. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89505. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89506. _this._dragBehaviorB.releaseDrag();
  89507. }
  89508. else {
  89509. _this._initialScale.copyFrom(ownerNode.scaling);
  89510. _this._startDistance = _this._getCurrentDistance();
  89511. }
  89512. }
  89513. });
  89514. // Once both drag behaviors are active scale based on the distance between the two pointers
  89515. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89516. behavior.onDragObservable.add(function () {
  89517. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89518. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89519. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89520. }
  89521. });
  89522. });
  89523. ownerNode.addBehavior(this._dragBehaviorA);
  89524. ownerNode.addBehavior(this._dragBehaviorB);
  89525. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89526. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89527. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89528. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89529. if (change.length() > 0.01) {
  89530. ownerNode.scaling.addInPlace(change);
  89531. }
  89532. }
  89533. });
  89534. };
  89535. /**
  89536. * Detaches the behavior from the mesh
  89537. */
  89538. MultiPointerScaleBehavior.prototype.detach = function () {
  89539. var _this = this;
  89540. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89541. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89542. behavior.onDragStartObservable.clear();
  89543. behavior.onDragObservable.clear();
  89544. _this._ownerNode.removeBehavior(behavior);
  89545. });
  89546. };
  89547. return MultiPointerScaleBehavior;
  89548. }());
  89549. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89550. })(BABYLON || (BABYLON = {}));
  89551. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89552. var BABYLON;
  89553. (function (BABYLON) {
  89554. /**
  89555. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  89556. */
  89557. var SixDofDragBehavior = /** @class */ (function () {
  89558. function SixDofDragBehavior() {
  89559. this._sceneRenderObserver = null;
  89560. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89561. this._moving = false;
  89562. this._startingOrientation = new BABYLON.Quaternion();
  89563. /**
  89564. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  89565. */
  89566. this.zDragFactor = 3;
  89567. /**
  89568. * If the behavior is currently in a dragging state
  89569. */
  89570. this.dragging = false;
  89571. /**
  89572. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89573. */
  89574. this.dragDeltaRatio = 0.2;
  89575. /**
  89576. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89577. */
  89578. this.currentDraggingPointerID = -1;
  89579. /**
  89580. * If camera controls should be detached during the drag
  89581. */
  89582. this.detachCameraControls = true;
  89583. }
  89584. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89585. /**
  89586. * The name of the behavior
  89587. */
  89588. get: function () {
  89589. return "SixDofDrag";
  89590. },
  89591. enumerable: true,
  89592. configurable: true
  89593. });
  89594. /**
  89595. * Initializes the behavior
  89596. */
  89597. SixDofDragBehavior.prototype.init = function () { };
  89598. /**
  89599. * Attaches the scale behavior the passed in mesh
  89600. * @param ownerNode The mesh that will be scaled around once attached
  89601. */
  89602. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89603. var _this = this;
  89604. this._ownerNode = ownerNode;
  89605. this._scene = this._ownerNode.getScene();
  89606. if (!SixDofDragBehavior._virtualScene) {
  89607. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89608. this._scene.getEngine().scenes.pop();
  89609. }
  89610. var pickedMesh = null;
  89611. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89612. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89613. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89614. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89615. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89616. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89617. var pickPredicate = function (m) {
  89618. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89619. };
  89620. var attachedElement = null;
  89621. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89622. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89623. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89624. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89625. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89626. }
  89627. pickedMesh = _this._ownerNode;
  89628. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89629. // Set position and orientation of the controller
  89630. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89631. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89632. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89633. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89634. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89635. if (!pickedMesh.rotationQuaternion) {
  89636. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89637. }
  89638. var oldParent = pickedMesh.parent;
  89639. pickedMesh.setParent(null);
  89640. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89641. pickedMesh.setParent(oldParent);
  89642. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89643. // Update state
  89644. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89645. _this.dragging = true;
  89646. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89647. // Detatch camera controls
  89648. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89649. if (_this._scene.activeCamera.inputs.attachedElement) {
  89650. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89651. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89652. }
  89653. else {
  89654. attachedElement = null;
  89655. }
  89656. }
  89657. }
  89658. }
  89659. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89660. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89661. _this.dragging = false;
  89662. _this._moving = false;
  89663. _this.currentDraggingPointerID = -1;
  89664. pickedMesh = null;
  89665. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89666. // Reattach camera controls
  89667. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89668. _this._scene.activeCamera.attachControl(attachedElement, true);
  89669. }
  89670. }
  89671. }
  89672. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89673. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89674. var zDragFactor = _this.zDragFactor;
  89675. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89676. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89677. zDragFactor = 0;
  89678. }
  89679. // Calculate controller drag distance in controller space
  89680. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89681. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89682. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  89683. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89684. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89685. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  89686. if (_this._virtualDragMesh.position.z < 0) {
  89687. _this._virtualDragMesh.position.z = 0;
  89688. }
  89689. // Update the controller position
  89690. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89691. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89692. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89693. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89694. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89695. if (pickedMesh.parent) {
  89696. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89697. }
  89698. if (!_this._moving) {
  89699. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89700. }
  89701. _this._moving = true;
  89702. }
  89703. }
  89704. });
  89705. var tmpQuaternion = new BABYLON.Quaternion();
  89706. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89707. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89708. if (_this.dragging && _this._moving && pickedMesh) {
  89709. // Slowly move mesh to avoid jitter
  89710. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89711. // Get change in rotation
  89712. tmpQuaternion.copyFrom(_this._startingOrientation);
  89713. tmpQuaternion.x = -tmpQuaternion.x;
  89714. tmpQuaternion.y = -tmpQuaternion.y;
  89715. tmpQuaternion.z = -tmpQuaternion.z;
  89716. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89717. // Convert change in rotation to only y axis rotation
  89718. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89719. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89720. // Slowly move mesh to avoid jitter
  89721. var oldParent = pickedMesh.parent;
  89722. pickedMesh.setParent(null);
  89723. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89724. pickedMesh.setParent(oldParent);
  89725. }
  89726. });
  89727. };
  89728. /**
  89729. * Detaches the behavior from the mesh
  89730. */
  89731. SixDofDragBehavior.prototype.detach = function () {
  89732. if (this._scene) {
  89733. this._scene.onPointerObservable.remove(this._pointerObserver);
  89734. }
  89735. if (this._ownerNode) {
  89736. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89737. }
  89738. if (this._virtualOriginMesh) {
  89739. this._virtualOriginMesh.dispose();
  89740. }
  89741. if (this._virtualDragMesh) {
  89742. this._virtualDragMesh.dispose();
  89743. }
  89744. };
  89745. return SixDofDragBehavior;
  89746. }());
  89747. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89748. })(BABYLON || (BABYLON = {}));
  89749. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89750. var BABYLON;
  89751. (function (BABYLON) {
  89752. /**
  89753. * @hidden
  89754. */
  89755. var FaceDirectionInfo = /** @class */ (function () {
  89756. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  89757. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  89758. if (diff === void 0) { diff = 0; }
  89759. if (ignore === void 0) { ignore = false; }
  89760. this.direction = direction;
  89761. this.rotatedDirection = rotatedDirection;
  89762. this.diff = diff;
  89763. this.ignore = ignore;
  89764. }
  89765. return FaceDirectionInfo;
  89766. }());
  89767. /**
  89768. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  89769. */
  89770. var AttachToBoxBehavior = /** @class */ (function () {
  89771. /**
  89772. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  89773. * @param ui The transform node that should be attched to the mesh
  89774. */
  89775. function AttachToBoxBehavior(ui) {
  89776. this.ui = ui;
  89777. /**
  89778. * The name of the behavior
  89779. */
  89780. this.name = "AttachToBoxBehavior";
  89781. /**
  89782. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  89783. */
  89784. this.distanceAwayFromFace = 0.15;
  89785. /**
  89786. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  89787. */
  89788. this.distanceAwayFromBottomOfFace = 0.15;
  89789. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  89790. this._tmpMatrix = new BABYLON.Matrix();
  89791. this._tmpVector = new BABYLON.Vector3();
  89792. this._zeroVector = BABYLON.Vector3.Zero();
  89793. this._lookAtTmpMatrix = new BABYLON.Matrix();
  89794. /* Does nothing */
  89795. }
  89796. /**
  89797. * Initializes the behavior
  89798. */
  89799. AttachToBoxBehavior.prototype.init = function () {
  89800. /* Does nothing */
  89801. };
  89802. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  89803. var _this = this;
  89804. // Go over each face and calculate the angle between the face's normal and targetDirection
  89805. this._faceVectors.forEach(function (v) {
  89806. if (!_this._target.rotationQuaternion) {
  89807. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  89808. }
  89809. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  89810. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  89811. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  89812. });
  89813. // Return the face information of the one with the normal closeset to target direction
  89814. return this._faceVectors.reduce(function (min, p) {
  89815. if (min.ignore) {
  89816. return p;
  89817. }
  89818. else if (p.ignore) {
  89819. return min;
  89820. }
  89821. else {
  89822. return min.diff < p.diff ? min : p;
  89823. }
  89824. }, this._faceVectors[0]);
  89825. };
  89826. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  89827. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  89828. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  89829. this._lookAtTmpMatrix.invert();
  89830. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  89831. };
  89832. /**
  89833. * Attaches the AttachToBoxBehavior to the passed in mesh
  89834. * @param target The mesh that the specified node will be attached to
  89835. */
  89836. AttachToBoxBehavior.prototype.attach = function (target) {
  89837. var _this = this;
  89838. this._target = target;
  89839. this._scene = this._target.getScene();
  89840. // Every frame, update the app bars position
  89841. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89842. if (!_this._scene.activeCamera) {
  89843. return;
  89844. }
  89845. // Find the face closest to the cameras position
  89846. var cameraPos = _this._scene.activeCamera.position;
  89847. if (_this._scene.activeCamera.devicePosition) {
  89848. cameraPos = _this._scene.activeCamera.devicePosition;
  89849. }
  89850. var facing = _this._closestFace(cameraPos.subtract(target.position));
  89851. if (_this._scene.activeCamera.leftCamera) {
  89852. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89853. }
  89854. else {
  89855. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89856. }
  89857. // Get camera up direction
  89858. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  89859. // Ignore faces to not select a parrelel face for the up vector of the UI
  89860. _this._faceVectors.forEach(function (v) {
  89861. if (facing.direction.x && v.direction.x) {
  89862. v.ignore = true;
  89863. }
  89864. if (facing.direction.y && v.direction.y) {
  89865. v.ignore = true;
  89866. }
  89867. if (facing.direction.z && v.direction.z) {
  89868. v.ignore = true;
  89869. }
  89870. });
  89871. var facingUp = _this._closestFace(_this._tmpVector);
  89872. // Unignore faces
  89873. _this._faceVectors.forEach(function (v) {
  89874. v.ignore = false;
  89875. });
  89876. // Position the app bar on that face
  89877. _this.ui.position.copyFrom(target.position);
  89878. if (facing.direction.x) {
  89879. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89880. _this.ui.position.addInPlace(_this._tmpVector);
  89881. }
  89882. if (facing.direction.y) {
  89883. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89884. _this.ui.position.addInPlace(_this._tmpVector);
  89885. }
  89886. if (facing.direction.z) {
  89887. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89888. _this.ui.position.addInPlace(_this._tmpVector);
  89889. }
  89890. // Rotate to be oriented properly to the camera
  89891. if (!_this.ui.rotationQuaternion) {
  89892. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  89893. }
  89894. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  89895. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  89896. // Place ui the correct distance from the bottom of the mesh
  89897. if (facingUp.direction.x) {
  89898. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  89899. }
  89900. if (facingUp.direction.y) {
  89901. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  89902. }
  89903. if (facingUp.direction.z) {
  89904. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  89905. }
  89906. _this.ui.position.addInPlace(_this._tmpVector);
  89907. });
  89908. };
  89909. /**
  89910. * Detaches the behavior from the mesh
  89911. */
  89912. AttachToBoxBehavior.prototype.detach = function () {
  89913. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  89914. };
  89915. return AttachToBoxBehavior;
  89916. }());
  89917. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  89918. })(BABYLON || (BABYLON = {}));
  89919. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  89920. var BABYLON;
  89921. (function (BABYLON) {
  89922. /**
  89923. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89924. */
  89925. var Gizmo = /** @class */ (function () {
  89926. /**
  89927. * Creates a gizmo
  89928. * @param gizmoLayer The utility layer the gizmo will be added to
  89929. */
  89930. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89931. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89932. var _this = this;
  89933. this.gizmoLayer = gizmoLayer;
  89934. this._scaleFactor = 3;
  89935. this._tmpMatrix = new BABYLON.Matrix();
  89936. /**
  89937. * If a custom mesh has been set (Default: false)
  89938. */
  89939. this._customMeshSet = false;
  89940. /**
  89941. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89942. */
  89943. this.updateGizmoRotationToMatchAttachedMesh = true;
  89944. /**
  89945. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89946. */
  89947. this.updateGizmoPositionToMatchAttachedMesh = true;
  89948. /**
  89949. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89950. */
  89951. this._updateScale = true;
  89952. this._interactionsEnabled = true;
  89953. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89954. var tempVector = new BABYLON.Vector3();
  89955. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89956. if (_this.attachedMesh) {
  89957. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89958. if (!_this._rootMesh.rotationQuaternion) {
  89959. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89960. }
  89961. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89962. tempVector.copyFrom(_this.attachedMesh.scaling);
  89963. if (_this.attachedMesh.scaling.x < 0) {
  89964. _this.attachedMesh.scaling.x *= -1;
  89965. }
  89966. if (_this.attachedMesh.scaling.y < 0) {
  89967. _this.attachedMesh.scaling.y *= -1;
  89968. }
  89969. if (_this.attachedMesh.scaling.z < 0) {
  89970. _this.attachedMesh.scaling.z *= -1;
  89971. }
  89972. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89973. _this.attachedMesh.scaling.copyFrom(tempVector);
  89974. _this.attachedMesh.computeWorldMatrix();
  89975. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  89976. }
  89977. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89978. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89979. }
  89980. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89981. var cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.position;
  89982. if (_this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  89983. cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  89984. }
  89985. _this._rootMesh.position.subtractToRef(cameraPosition, tempVector);
  89986. var dist = tempVector.length() / _this._scaleFactor;
  89987. _this._rootMesh.scaling.set(dist, dist, dist);
  89988. }
  89989. }
  89990. });
  89991. this.attachedMesh = null;
  89992. }
  89993. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89994. /**
  89995. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89996. * * When set, interactions will be enabled
  89997. */
  89998. get: function () {
  89999. return this._attachedMesh;
  90000. },
  90001. set: function (value) {
  90002. this._attachedMesh = value;
  90003. this._rootMesh.setEnabled(value ? true : false);
  90004. this._attachedMeshChanged(value);
  90005. },
  90006. enumerable: true,
  90007. configurable: true
  90008. });
  90009. /**
  90010. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  90011. * @param mesh The mesh to replace the default mesh of the gizmo
  90012. */
  90013. Gizmo.prototype.setCustomMesh = function (mesh) {
  90014. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  90015. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  90016. }
  90017. this._rootMesh.getChildMeshes().forEach(function (c) {
  90018. c.dispose();
  90019. });
  90020. mesh.parent = this._rootMesh;
  90021. this._customMeshSet = true;
  90022. };
  90023. Gizmo.prototype._attachedMeshChanged = function (value) {
  90024. };
  90025. /**
  90026. * Disposes of the gizmo
  90027. */
  90028. Gizmo.prototype.dispose = function () {
  90029. this._rootMesh.dispose();
  90030. if (this._beforeRenderObserver) {
  90031. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90032. }
  90033. };
  90034. return Gizmo;
  90035. }());
  90036. BABYLON.Gizmo = Gizmo;
  90037. })(BABYLON || (BABYLON = {}));
  90038. //# sourceMappingURL=babylon.gizmo.js.map
  90039. var BABYLON;
  90040. (function (BABYLON) {
  90041. /**
  90042. * Single axis drag gizmo
  90043. */
  90044. var AxisDragGizmo = /** @class */ (function (_super) {
  90045. __extends(AxisDragGizmo, _super);
  90046. /**
  90047. * Creates an AxisDragGizmo
  90048. * @param gizmoLayer The utility layer the gizmo will be added to
  90049. * @param dragAxis The axis which the gizmo will be able to drag on
  90050. * @param color The color of the gizmo
  90051. */
  90052. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  90053. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90054. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90055. var _this = _super.call(this, gizmoLayer) || this;
  90056. _this._pointerObserver = null;
  90057. /**
  90058. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90059. */
  90060. _this.snapDistance = 0;
  90061. /**
  90062. * Event that fires each time the gizmo snaps to a new location.
  90063. * * snapDistance is the the change in distance
  90064. */
  90065. _this.onSnapObservable = new BABYLON.Observable();
  90066. // Create Material
  90067. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90068. coloredMaterial.disableLighting = true;
  90069. coloredMaterial.emissiveColor = color;
  90070. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90071. hoverMaterial.disableLighting = true;
  90072. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90073. // Build mesh on root node
  90074. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90075. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90076. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90077. arrow.addChild(arrowMesh);
  90078. arrow.addChild(arrowTail);
  90079. // Position arrow pointing in its drag axis
  90080. arrowMesh.scaling.scaleInPlace(0.05);
  90081. arrowMesh.material = coloredMaterial;
  90082. arrowMesh.rotation.x = Math.PI / 2;
  90083. arrowMesh.position.z += 0.3;
  90084. arrowTail.rotation.x = Math.PI / 2;
  90085. arrowTail.material = coloredMaterial;
  90086. arrowTail.position.z += 0.15;
  90087. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90088. _this._rootMesh.addChild(arrow);
  90089. var currentSnapDragDistance = 0;
  90090. var tmpVector = new BABYLON.Vector3();
  90091. var tmpSnapEvent = { snapDistance: 0 };
  90092. // Add drag behavior to handle events when the gizmo is dragged
  90093. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90094. _this.dragBehavior.moveAttached = false;
  90095. _this._rootMesh.addBehavior(_this.dragBehavior);
  90096. _this.dragBehavior.onDragObservable.add(function (event) {
  90097. if (_this.attachedMesh) {
  90098. // Snapping logic
  90099. if (_this.snapDistance == 0) {
  90100. _this.attachedMesh.position.addInPlace(event.delta);
  90101. }
  90102. else {
  90103. currentSnapDragDistance += event.dragDistance;
  90104. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90105. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  90106. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90107. event.delta.normalizeToRef(tmpVector);
  90108. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  90109. _this.attachedMesh.position.addInPlace(tmpVector);
  90110. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90111. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90112. }
  90113. }
  90114. }
  90115. });
  90116. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90117. if (_this._customMeshSet) {
  90118. return;
  90119. }
  90120. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90121. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90122. m.material = hoverMaterial;
  90123. });
  90124. }
  90125. else {
  90126. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90127. m.material = coloredMaterial;
  90128. });
  90129. }
  90130. });
  90131. return _this;
  90132. }
  90133. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  90134. if (this.dragBehavior) {
  90135. this.dragBehavior.enabled = value ? true : false;
  90136. }
  90137. };
  90138. /**
  90139. * Disposes of the gizmo
  90140. */
  90141. AxisDragGizmo.prototype.dispose = function () {
  90142. this.onSnapObservable.clear();
  90143. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90144. this.dragBehavior.detach();
  90145. _super.prototype.dispose.call(this);
  90146. };
  90147. return AxisDragGizmo;
  90148. }(BABYLON.Gizmo));
  90149. BABYLON.AxisDragGizmo = AxisDragGizmo;
  90150. })(BABYLON || (BABYLON = {}));
  90151. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  90152. var BABYLON;
  90153. (function (BABYLON) {
  90154. /**
  90155. * Single axis scale gizmo
  90156. */
  90157. var AxisScaleGizmo = /** @class */ (function (_super) {
  90158. __extends(AxisScaleGizmo, _super);
  90159. /**
  90160. * Creates an AxisScaleGizmo
  90161. * @param gizmoLayer The utility layer the gizmo will be added to
  90162. * @param dragAxis The axis which the gizmo will be able to scale on
  90163. * @param color The color of the gizmo
  90164. */
  90165. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  90166. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90167. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90168. var _this = _super.call(this, gizmoLayer) || this;
  90169. _this._pointerObserver = null;
  90170. /**
  90171. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90172. */
  90173. _this.snapDistance = 0;
  90174. /**
  90175. * Event that fires each time the gizmo snaps to a new location.
  90176. * * snapDistance is the the change in distance
  90177. */
  90178. _this.onSnapObservable = new BABYLON.Observable();
  90179. // Create Material
  90180. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90181. coloredMaterial.disableLighting = true;
  90182. coloredMaterial.emissiveColor = color;
  90183. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90184. hoverMaterial.disableLighting = true;
  90185. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90186. // Build mesh on root node
  90187. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90188. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  90189. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90190. arrow.addChild(arrowMesh);
  90191. arrow.addChild(arrowTail);
  90192. // Position arrow pointing in its drag axis
  90193. arrowMesh.scaling.scaleInPlace(0.1);
  90194. arrowMesh.material = coloredMaterial;
  90195. arrowMesh.rotation.x = Math.PI / 2;
  90196. arrowMesh.position.z += 0.3;
  90197. arrowTail.rotation.x = Math.PI / 2;
  90198. arrowTail.material = coloredMaterial;
  90199. arrowTail.position.z += 0.15;
  90200. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90201. _this._rootMesh.addChild(arrow);
  90202. // Add drag behavior to handle events when the gizmo is dragged
  90203. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90204. _this.dragBehavior.moveAttached = false;
  90205. _this._rootMesh.addBehavior(_this.dragBehavior);
  90206. var currentSnapDragDistance = 0;
  90207. var tmpVector = new BABYLON.Vector3();
  90208. var tmpSnapEvent = { snapDistance: 0 };
  90209. _this.dragBehavior.onDragObservable.add(function (event) {
  90210. if (_this.attachedMesh) {
  90211. // Snapping logic
  90212. var snapped = false;
  90213. var dragSteps = 0;
  90214. if (_this.snapDistance == 0) {
  90215. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  90216. }
  90217. else {
  90218. currentSnapDragDistance += event.dragDistance;
  90219. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90220. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90221. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90222. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  90223. snapped = true;
  90224. }
  90225. else {
  90226. tmpVector.scaleInPlace(0);
  90227. }
  90228. }
  90229. _this.attachedMesh.scaling.addInPlace(tmpVector);
  90230. if (snapped) {
  90231. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90232. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90233. }
  90234. }
  90235. });
  90236. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90237. if (_this._customMeshSet) {
  90238. return;
  90239. }
  90240. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90241. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90242. m.material = hoverMaterial;
  90243. });
  90244. }
  90245. else {
  90246. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90247. m.material = coloredMaterial;
  90248. });
  90249. }
  90250. });
  90251. return _this;
  90252. }
  90253. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  90254. if (this.dragBehavior) {
  90255. this.dragBehavior.enabled = value ? true : false;
  90256. }
  90257. };
  90258. /**
  90259. * Disposes of the gizmo
  90260. */
  90261. AxisScaleGizmo.prototype.dispose = function () {
  90262. this.onSnapObservable.clear();
  90263. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90264. this.dragBehavior.detach();
  90265. _super.prototype.dispose.call(this);
  90266. };
  90267. return AxisScaleGizmo;
  90268. }(BABYLON.Gizmo));
  90269. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  90270. })(BABYLON || (BABYLON = {}));
  90271. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  90272. var BABYLON;
  90273. (function (BABYLON) {
  90274. /**
  90275. * Single plane rotation gizmo
  90276. */
  90277. var PlaneRotationGizmo = /** @class */ (function (_super) {
  90278. __extends(PlaneRotationGizmo, _super);
  90279. /**
  90280. * Creates a PlaneRotationGizmo
  90281. * @param gizmoLayer The utility layer the gizmo will be added to
  90282. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  90283. * @param color The color of the gizmo
  90284. */
  90285. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  90286. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90287. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90288. var _this = _super.call(this, gizmoLayer) || this;
  90289. _this._pointerObserver = null;
  90290. /**
  90291. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  90292. */
  90293. _this.snapDistance = 0;
  90294. /**
  90295. * Event that fires each time the gizmo snaps to a new location.
  90296. * * snapDistance is the the change in distance
  90297. */
  90298. _this.onSnapObservable = new BABYLON.Observable();
  90299. // Create Material
  90300. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90301. coloredMaterial.disableLighting = true;
  90302. coloredMaterial.emissiveColor = color;
  90303. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90304. hoverMaterial.disableLighting = true;
  90305. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90306. // Build mesh on root node
  90307. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90308. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  90309. // Position arrow pointing in its drag axis
  90310. rotationMesh.scaling.scaleInPlace(0.1);
  90311. rotationMesh.material = coloredMaterial;
  90312. rotationMesh.rotation.x = Math.PI / 2;
  90313. parentMesh.addChild(rotationMesh);
  90314. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  90315. _this._rootMesh.addChild(parentMesh);
  90316. // Add drag behavior to handle events when the gizmo is dragged
  90317. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  90318. _this.dragBehavior.moveAttached = false;
  90319. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  90320. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  90321. _this._rootMesh.addBehavior(_this.dragBehavior);
  90322. var lastDragPosition = new BABYLON.Vector3();
  90323. _this.dragBehavior.onDragStartObservable.add(function (e) {
  90324. if (_this.attachedMesh) {
  90325. lastDragPosition.copyFrom(e.dragPlanePoint);
  90326. }
  90327. });
  90328. var rotationMatrix = new BABYLON.Matrix();
  90329. var planeNormalTowardsCamera = new BABYLON.Vector3();
  90330. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  90331. var tmpSnapEvent = { snapDistance: 0 };
  90332. var currentSnapDragDistance = 0;
  90333. _this.dragBehavior.onDragObservable.add(function (event) {
  90334. if (_this.attachedMesh) {
  90335. if (!_this.attachedMesh.rotationQuaternion) {
  90336. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90337. }
  90338. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  90339. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  90340. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  90341. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  90342. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  90343. var angle = Math.atan2(cross.length(), dot);
  90344. planeNormalTowardsCamera.copyFrom(planeNormal);
  90345. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  90346. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90347. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  90348. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  90349. }
  90350. // Flip up vector depending on which side the camera is on
  90351. if (gizmoLayer.utilityLayerScene.activeCamera) {
  90352. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  90353. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  90354. planeNormalTowardsCamera.scaleInPlace(-1);
  90355. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  90356. }
  90357. }
  90358. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  90359. if (halfCircleSide)
  90360. angle = -angle;
  90361. // Snapping logic
  90362. var snapped = false;
  90363. if (_this.snapDistance != 0) {
  90364. currentSnapDragDistance += angle;
  90365. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90366. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90367. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90368. angle = _this.snapDistance * dragSteps;
  90369. snapped = true;
  90370. }
  90371. else {
  90372. angle = 0;
  90373. }
  90374. }
  90375. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  90376. var quaternionCoefficient = Math.sin(angle / 2);
  90377. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  90378. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90379. // Rotate selected mesh quaternion over fixed axis
  90380. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  90381. }
  90382. else {
  90383. // Rotate selected mesh quaternion over rotated axis
  90384. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  90385. }
  90386. lastDragPosition.copyFrom(event.dragPlanePoint);
  90387. if (snapped) {
  90388. tmpSnapEvent.snapDistance = angle;
  90389. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90390. }
  90391. }
  90392. });
  90393. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90394. if (_this._customMeshSet) {
  90395. return;
  90396. }
  90397. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  90398. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90399. m.material = hoverMaterial;
  90400. });
  90401. }
  90402. else {
  90403. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90404. m.material = coloredMaterial;
  90405. });
  90406. }
  90407. });
  90408. return _this;
  90409. }
  90410. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  90411. if (this.dragBehavior) {
  90412. this.dragBehavior.enabled = value ? true : false;
  90413. }
  90414. };
  90415. /**
  90416. * Disposes of the gizmo
  90417. */
  90418. PlaneRotationGizmo.prototype.dispose = function () {
  90419. this.onSnapObservable.clear();
  90420. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90421. this.dragBehavior.detach();
  90422. _super.prototype.dispose.call(this);
  90423. };
  90424. return PlaneRotationGizmo;
  90425. }(BABYLON.Gizmo));
  90426. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  90427. })(BABYLON || (BABYLON = {}));
  90428. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  90429. var BABYLON;
  90430. (function (BABYLON) {
  90431. /**
  90432. * Gizmo that enables dragging a mesh along 3 axis
  90433. */
  90434. var PositionGizmo = /** @class */ (function (_super) {
  90435. __extends(PositionGizmo, _super);
  90436. /**
  90437. * Creates a PositionGizmo
  90438. * @param gizmoLayer The utility layer the gizmo will be added to
  90439. */
  90440. function PositionGizmo(gizmoLayer) {
  90441. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90442. var _this = _super.call(this, gizmoLayer) || this;
  90443. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90444. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90445. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90446. _this.attachedMesh = null;
  90447. return _this;
  90448. }
  90449. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  90450. set: function (mesh) {
  90451. if (this.xGizmo) {
  90452. this.xGizmo.attachedMesh = mesh;
  90453. this.yGizmo.attachedMesh = mesh;
  90454. this.zGizmo.attachedMesh = mesh;
  90455. }
  90456. },
  90457. enumerable: true,
  90458. configurable: true
  90459. });
  90460. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90461. get: function () {
  90462. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90463. },
  90464. set: function (value) {
  90465. if (this.xGizmo) {
  90466. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90467. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90468. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90469. }
  90470. },
  90471. enumerable: true,
  90472. configurable: true
  90473. });
  90474. /**
  90475. * Disposes of the gizmo
  90476. */
  90477. PositionGizmo.prototype.dispose = function () {
  90478. this.xGizmo.dispose();
  90479. this.yGizmo.dispose();
  90480. this.zGizmo.dispose();
  90481. };
  90482. /**
  90483. * CustomMeshes are not supported by this gizmo
  90484. * @param mesh The mesh to replace the default mesh of the gizmo
  90485. */
  90486. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  90487. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  90488. };
  90489. return PositionGizmo;
  90490. }(BABYLON.Gizmo));
  90491. BABYLON.PositionGizmo = PositionGizmo;
  90492. })(BABYLON || (BABYLON = {}));
  90493. //# sourceMappingURL=babylon.positionGizmo.js.map
  90494. var BABYLON;
  90495. (function (BABYLON) {
  90496. /**
  90497. * Gizmo that enables rotating a mesh along 3 axis
  90498. */
  90499. var RotationGizmo = /** @class */ (function (_super) {
  90500. __extends(RotationGizmo, _super);
  90501. /**
  90502. * Creates a RotationGizmo
  90503. * @param gizmoLayer The utility layer the gizmo will be added to
  90504. */
  90505. function RotationGizmo(gizmoLayer) {
  90506. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90507. var _this = _super.call(this, gizmoLayer) || this;
  90508. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90509. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90510. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90511. _this.attachedMesh = null;
  90512. return _this;
  90513. }
  90514. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  90515. set: function (mesh) {
  90516. if (this.xGizmo) {
  90517. this.xGizmo.attachedMesh = mesh;
  90518. this.yGizmo.attachedMesh = mesh;
  90519. this.zGizmo.attachedMesh = mesh;
  90520. }
  90521. },
  90522. enumerable: true,
  90523. configurable: true
  90524. });
  90525. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90526. get: function () {
  90527. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90528. },
  90529. set: function (value) {
  90530. if (this.xGizmo) {
  90531. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90532. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90533. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90534. }
  90535. },
  90536. enumerable: true,
  90537. configurable: true
  90538. });
  90539. /**
  90540. * Disposes of the gizmo
  90541. */
  90542. RotationGizmo.prototype.dispose = function () {
  90543. this.xGizmo.dispose();
  90544. this.yGizmo.dispose();
  90545. this.zGizmo.dispose();
  90546. };
  90547. /**
  90548. * CustomMeshes are not supported by this gizmo
  90549. * @param mesh The mesh to replace the default mesh of the gizmo
  90550. */
  90551. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  90552. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  90553. };
  90554. return RotationGizmo;
  90555. }(BABYLON.Gizmo));
  90556. BABYLON.RotationGizmo = RotationGizmo;
  90557. })(BABYLON || (BABYLON = {}));
  90558. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90559. var BABYLON;
  90560. (function (BABYLON) {
  90561. /**
  90562. * Gizmo that enables scaling a mesh along 3 axis
  90563. */
  90564. var ScaleGizmo = /** @class */ (function (_super) {
  90565. __extends(ScaleGizmo, _super);
  90566. /**
  90567. * Creates a ScaleGizmo
  90568. * @param gizmoLayer The utility layer the gizmo will be added to
  90569. */
  90570. function ScaleGizmo(gizmoLayer) {
  90571. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90572. var _this = _super.call(this, gizmoLayer) || this;
  90573. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90574. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90575. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90576. _this.attachedMesh = null;
  90577. return _this;
  90578. }
  90579. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90580. set: function (mesh) {
  90581. if (this.xGizmo) {
  90582. this.xGizmo.attachedMesh = mesh;
  90583. this.yGizmo.attachedMesh = mesh;
  90584. this.zGizmo.attachedMesh = mesh;
  90585. }
  90586. },
  90587. enumerable: true,
  90588. configurable: true
  90589. });
  90590. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90591. get: function () {
  90592. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90593. },
  90594. set: function (value) {
  90595. if (this.xGizmo) {
  90596. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90597. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90598. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90599. }
  90600. },
  90601. enumerable: true,
  90602. configurable: true
  90603. });
  90604. /**
  90605. * Disposes of the gizmo
  90606. */
  90607. ScaleGizmo.prototype.dispose = function () {
  90608. this.xGizmo.dispose();
  90609. this.yGizmo.dispose();
  90610. this.zGizmo.dispose();
  90611. };
  90612. return ScaleGizmo;
  90613. }(BABYLON.Gizmo));
  90614. BABYLON.ScaleGizmo = ScaleGizmo;
  90615. })(BABYLON || (BABYLON = {}));
  90616. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90617. var BABYLON;
  90618. (function (BABYLON) {
  90619. /**
  90620. * Bounding box gizmo
  90621. */
  90622. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90623. __extends(BoundingBoxGizmo, _super);
  90624. /**
  90625. * Creates an BoundingBoxGizmo
  90626. * @param gizmoLayer The utility layer the gizmo will be added to
  90627. * @param color The color of the gizmo
  90628. */
  90629. function BoundingBoxGizmo(color, gizmoLayer) {
  90630. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90631. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  90632. var _this = _super.call(this, gizmoLayer) || this;
  90633. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90634. _this._renderObserver = null;
  90635. _this._pointerObserver = null;
  90636. _this._scaleDragSpeed = 0.2;
  90637. _this._tmpQuaternion = new BABYLON.Quaternion();
  90638. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90639. /**
  90640. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90641. */
  90642. _this.rotationSphereSize = 0.1;
  90643. /**
  90644. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90645. */
  90646. _this.scaleBoxSize = 0.1;
  90647. /**
  90648. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  90649. */
  90650. _this.fixedDragMeshScreenSize = false;
  90651. /**
  90652. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90653. */
  90654. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90655. /**
  90656. * Fired when a rotation sphere or scale box is dragged
  90657. */
  90658. _this.onDragStartObservable = new BABYLON.Observable();
  90659. /**
  90660. * Fired when a rotation sphere or scale box drag is started
  90661. */
  90662. _this.onDragObservable = new BABYLON.Observable();
  90663. /**
  90664. * Fired when a rotation sphere or scale box drag is needed
  90665. */
  90666. _this.onDragEndObservable = new BABYLON.Observable();
  90667. _this._existingMeshScale = new BABYLON.Vector3();
  90668. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90669. _this._updateScale = false;
  90670. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  90671. // Create Materials
  90672. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90673. coloredMaterial.disableLighting = true;
  90674. coloredMaterial.emissiveColor = color;
  90675. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90676. hoverColoredMaterial.disableLighting = true;
  90677. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90678. // Build bounding box out of lines
  90679. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90680. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90681. var lines = [];
  90682. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90683. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90684. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90685. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90686. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90687. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90688. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90689. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90690. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90691. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90692. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90693. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90694. lines.forEach(function (l) {
  90695. l.color = color;
  90696. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90697. l.isPickable = false;
  90698. _this._lineBoundingBox.addChild(l);
  90699. });
  90700. _this._rootMesh.addChild(_this._lineBoundingBox);
  90701. // Create rotation spheres
  90702. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90703. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90704. var _loop_1 = function (i_1) {
  90705. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90706. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90707. sphere.material = coloredMaterial;
  90708. // Drag behavior
  90709. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90710. _dragBehavior.moveAttached = false;
  90711. _dragBehavior.updateDragPlane = false;
  90712. sphere.addBehavior(_dragBehavior);
  90713. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90714. var totalTurnAmountOfDrag = 0;
  90715. _dragBehavior.onDragStartObservable.add(function (event) {
  90716. startingTurnDirection.copyFrom(sphere.forward);
  90717. totalTurnAmountOfDrag = 0;
  90718. });
  90719. _dragBehavior.onDragObservable.add(function (event) {
  90720. _this.onDragObservable.notifyObservers({});
  90721. if (_this.attachedMesh) {
  90722. var worldDragDirection = startingTurnDirection;
  90723. // Project the world right on to the drag plane
  90724. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90725. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90726. // project drag delta on to the resulting drag axis and rotate based on that
  90727. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90728. // Rotate based on axis
  90729. if (!_this.attachedMesh.rotationQuaternion) {
  90730. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90731. }
  90732. if (!_this._anchorMesh.rotationQuaternion) {
  90733. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  90734. }
  90735. // Do not allow the object to turn more than a full circle
  90736. totalTurnAmountOfDrag += projectDist;
  90737. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90738. if (i_1 >= 8) {
  90739. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90740. }
  90741. else if (i_1 >= 4) {
  90742. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90743. }
  90744. else {
  90745. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90746. }
  90747. // Rotate around center of bounding box
  90748. _this._anchorMesh.addChild(_this.attachedMesh);
  90749. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  90750. _this._anchorMesh.removeChild(_this.attachedMesh);
  90751. }
  90752. _this.updateBoundingBox();
  90753. }
  90754. });
  90755. // Selection/deselection
  90756. _dragBehavior.onDragStartObservable.add(function () {
  90757. _this.onDragStartObservable.notifyObservers({});
  90758. _this._selectNode(sphere);
  90759. });
  90760. _dragBehavior.onDragEndObservable.add(function () {
  90761. _this.onDragEndObservable.notifyObservers({});
  90762. _this._selectNode(null);
  90763. });
  90764. this_1._rotateSpheresParent.addChild(sphere);
  90765. };
  90766. var this_1 = this, _dragBehavior;
  90767. for (var i_1 = 0; i_1 < 12; i_1++) {
  90768. _loop_1(i_1);
  90769. }
  90770. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90771. // Create scale cubes
  90772. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90773. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90774. for (var i = 0; i < 2; i++) {
  90775. for (var j = 0; j < 2; j++) {
  90776. var _loop_2 = function () {
  90777. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90778. box.material = coloredMaterial;
  90779. // Dragging logic
  90780. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90781. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90782. _dragBehavior.moveAttached = false;
  90783. box.addBehavior(_dragBehavior);
  90784. _dragBehavior.onDragObservable.add(function (event) {
  90785. _this.onDragObservable.notifyObservers({});
  90786. if (_this.attachedMesh) {
  90787. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90788. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90789. _this.updateBoundingBox();
  90790. // Scale from the position of the opposite corner
  90791. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  90792. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  90793. _this._anchorMesh.addChild(_this.attachedMesh);
  90794. _this._anchorMesh.scaling.addInPlace(deltaScale);
  90795. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  90796. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  90797. }
  90798. _this._anchorMesh.removeChild(_this.attachedMesh);
  90799. }
  90800. });
  90801. // Selection/deselection
  90802. _dragBehavior.onDragStartObservable.add(function () {
  90803. _this.onDragStartObservable.notifyObservers({});
  90804. _this._selectNode(box);
  90805. });
  90806. _dragBehavior.onDragEndObservable.add(function () {
  90807. _this.onDragEndObservable.notifyObservers({});
  90808. _this._selectNode(null);
  90809. });
  90810. this_2._scaleBoxesParent.addChild(box);
  90811. };
  90812. var this_2 = this, _dragBehavior;
  90813. for (var k = 0; k < 2; k++) {
  90814. _loop_2();
  90815. }
  90816. }
  90817. }
  90818. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90819. // Hover color change
  90820. var pointerIds = new Array();
  90821. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90822. if (!pointerIds[pointerInfo.event.pointerId]) {
  90823. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90824. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90825. pointerIds[pointerInfo.event.pointerId] = mesh;
  90826. mesh.material = hoverColoredMaterial;
  90827. }
  90828. });
  90829. }
  90830. else {
  90831. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90832. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90833. delete pointerIds[pointerInfo.event.pointerId];
  90834. }
  90835. }
  90836. });
  90837. // Update bounding box positions
  90838. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90839. // Only update the bouding box if scaling has changed
  90840. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  90841. _this.updateBoundingBox();
  90842. }
  90843. });
  90844. _this.updateBoundingBox();
  90845. return _this;
  90846. }
  90847. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  90848. if (value) {
  90849. // Reset anchor mesh to match attached mesh's scale
  90850. // This is needed to avoid invalid box/sphere position on first drag
  90851. this._anchorMesh.addChild(value);
  90852. this._anchorMesh.removeChild(value);
  90853. this.updateBoundingBox();
  90854. }
  90855. };
  90856. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90857. this._rotateSpheresParent.getChildMeshes()
  90858. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90859. m.isVisible = (!selectedMesh || m == selectedMesh);
  90860. });
  90861. };
  90862. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  90863. var _this = this;
  90864. mesh.computeWorldMatrix(true);
  90865. mesh.getChildMeshes().forEach(function (m) {
  90866. _this._recurseComputeWorld(m);
  90867. });
  90868. };
  90869. /**
  90870. * Updates the bounding box information for the Gizmo
  90871. */
  90872. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  90873. if (this.attachedMesh) {
  90874. // Rotate based on axis
  90875. if (!this.attachedMesh.rotationQuaternion) {
  90876. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  90877. }
  90878. if (!this._anchorMesh.rotationQuaternion) {
  90879. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  90880. }
  90881. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90882. // Store original position and reset mesh to origin before computing the bounding box
  90883. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90884. this._tmpVector.copyFrom(this.attachedMesh.position);
  90885. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  90886. this.attachedMesh.position.set(0, 0, 0);
  90887. // Update bounding dimensions/positions
  90888. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  90889. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  90890. // Update gizmo to match bounding box scaling and rotation
  90891. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90892. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  90893. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  90894. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  90895. this._lineBoundingBox.computeWorldMatrix();
  90896. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  90897. // restore position/rotation values
  90898. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  90899. this.attachedMesh.position.copyFrom(this._tmpVector);
  90900. this._recurseComputeWorld(this.attachedMesh);
  90901. }
  90902. // Update rotation sphere locations
  90903. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90904. for (var i = 0; i < 3; i++) {
  90905. for (var j = 0; j < 2; j++) {
  90906. for (var k = 0; k < 2; k++) {
  90907. var index = ((i * 4) + (j * 2)) + k;
  90908. if (i == 0) {
  90909. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90910. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90911. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90912. }
  90913. if (i == 1) {
  90914. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90915. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90916. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90917. }
  90918. if (i == 2) {
  90919. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90920. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90921. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90922. }
  90923. if (this.fixedDragMeshScreenSize) {
  90924. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90925. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90926. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90927. }
  90928. else {
  90929. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90930. }
  90931. }
  90932. }
  90933. }
  90934. // Update scale box locations
  90935. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90936. for (var i = 0; i < 2; i++) {
  90937. for (var j = 0; j < 2; j++) {
  90938. for (var k = 0; k < 2; k++) {
  90939. var index = ((i * 4) + (j * 2)) + k;
  90940. if (scaleBoxes[index]) {
  90941. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90942. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90943. if (this.fixedDragMeshScreenSize) {
  90944. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90945. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90946. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90947. }
  90948. else {
  90949. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90950. }
  90951. }
  90952. }
  90953. }
  90954. }
  90955. if (this.attachedMesh) {
  90956. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  90957. }
  90958. };
  90959. /**
  90960. * Enables rotation on the specified axis and disables rotation on the others
  90961. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90962. */
  90963. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90964. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90965. if (i < 4) {
  90966. m.setEnabled(axis.indexOf("x") != -1);
  90967. }
  90968. else if (i < 8) {
  90969. m.setEnabled(axis.indexOf("y") != -1);
  90970. }
  90971. else {
  90972. m.setEnabled(axis.indexOf("z") != -1);
  90973. }
  90974. });
  90975. };
  90976. /**
  90977. * Disposes of the gizmo
  90978. */
  90979. BoundingBoxGizmo.prototype.dispose = function () {
  90980. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90981. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90982. this._lineBoundingBox.dispose();
  90983. this._rotateSpheresParent.dispose();
  90984. this._scaleBoxesParent.dispose();
  90985. _super.prototype.dispose.call(this);
  90986. };
  90987. /**
  90988. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  90989. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  90990. * @returns the bounding box mesh with the passed in mesh as a child
  90991. */
  90992. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  90993. var makeNotPickable = function (root) {
  90994. root.isPickable = false;
  90995. root.getChildMeshes().forEach(function (c) {
  90996. makeNotPickable(c);
  90997. });
  90998. };
  90999. makeNotPickable(mesh);
  91000. // Reset position to get boudning box from origin with no rotation
  91001. if (!mesh.rotationQuaternion) {
  91002. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  91003. }
  91004. var oldPos = mesh.position.clone();
  91005. var oldRot = mesh.rotationQuaternion.clone();
  91006. mesh.rotationQuaternion.set(0, 0, 0, 1);
  91007. mesh.position.set(0, 0, 0);
  91008. // Update bounding dimensions/positions
  91009. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  91010. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  91011. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  91012. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  91013. // Restore original positions
  91014. mesh.addChild(box);
  91015. mesh.rotationQuaternion.copyFrom(oldRot);
  91016. mesh.position.copyFrom(oldPos);
  91017. // Reverse parenting
  91018. mesh.removeChild(box);
  91019. box.addChild(mesh);
  91020. box.visibility = 0;
  91021. return box;
  91022. };
  91023. /**
  91024. * CustomMeshes are not supported by this gizmo
  91025. * @param mesh The mesh to replace the default mesh of the gizmo
  91026. */
  91027. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  91028. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  91029. };
  91030. return BoundingBoxGizmo;
  91031. }(BABYLON.Gizmo));
  91032. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  91033. })(BABYLON || (BABYLON = {}));
  91034. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  91035. var BABYLON;
  91036. (function (BABYLON) {
  91037. /**
  91038. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  91039. */
  91040. var GizmoManager = /** @class */ (function () {
  91041. /**
  91042. * Instatiates a gizmo manager
  91043. * @param scene the scene to overlay the gizmos on top of
  91044. */
  91045. function GizmoManager(scene) {
  91046. var _this = this;
  91047. this.scene = scene;
  91048. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  91049. this._pointerObserver = null;
  91050. this._attachedMesh = null;
  91051. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  91052. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  91053. /**
  91054. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  91055. */
  91056. this.attachableMeshes = null;
  91057. /**
  91058. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  91059. */
  91060. this.usePointerToAttachGizmos = true;
  91061. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  91062. // Instatiate/dispose gizmos based on pointer actions
  91063. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  91064. if (!_this.usePointerToAttachGizmos) {
  91065. return;
  91066. }
  91067. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91068. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  91069. var node = pointerInfo.pickInfo.pickedMesh;
  91070. if (_this.attachableMeshes == null) {
  91071. // Attach to the most parent node
  91072. while (node && node.parent != null) {
  91073. node = node.parent;
  91074. }
  91075. }
  91076. else {
  91077. // Attach to the parent node that is an attachableMesh
  91078. var found = false;
  91079. _this.attachableMeshes.forEach(function (mesh) {
  91080. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  91081. node = mesh;
  91082. found = true;
  91083. }
  91084. });
  91085. if (!found) {
  91086. node = null;
  91087. }
  91088. }
  91089. if (node instanceof BABYLON.AbstractMesh) {
  91090. _this.attachToMesh(node);
  91091. }
  91092. }
  91093. else {
  91094. _this.attachToMesh(null);
  91095. }
  91096. }
  91097. });
  91098. }
  91099. /**
  91100. * Attaches a set of gizmos to the specified mesh
  91101. * @param mesh The mesh the gizmo's should be attached to
  91102. */
  91103. GizmoManager.prototype.attachToMesh = function (mesh) {
  91104. if (this._attachedMesh) {
  91105. this._attachedMesh.removeBehavior(this._dragBehavior);
  91106. }
  91107. this._attachedMesh = mesh;
  91108. for (var key in this.gizmos) {
  91109. var gizmo = (this.gizmos[key]);
  91110. if (gizmo && this._gizmosEnabled[key]) {
  91111. gizmo.attachedMesh = mesh;
  91112. }
  91113. }
  91114. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  91115. this._attachedMesh.addBehavior(this._dragBehavior);
  91116. }
  91117. };
  91118. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  91119. get: function () {
  91120. return this._gizmosEnabled.positionGizmo;
  91121. },
  91122. /**
  91123. * If the position gizmo is enabled
  91124. */
  91125. set: function (value) {
  91126. if (value) {
  91127. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  91128. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91129. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  91130. }
  91131. else if (this.gizmos.positionGizmo) {
  91132. this.gizmos.positionGizmo.attachedMesh = null;
  91133. }
  91134. this._gizmosEnabled.positionGizmo = value;
  91135. },
  91136. enumerable: true,
  91137. configurable: true
  91138. });
  91139. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  91140. get: function () {
  91141. return this._gizmosEnabled.rotationGizmo;
  91142. },
  91143. /**
  91144. * If the rotation gizmo is enabled
  91145. */
  91146. set: function (value) {
  91147. if (value) {
  91148. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  91149. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91150. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  91151. }
  91152. else if (this.gizmos.rotationGizmo) {
  91153. this.gizmos.rotationGizmo.attachedMesh = null;
  91154. }
  91155. this._gizmosEnabled.rotationGizmo = value;
  91156. },
  91157. enumerable: true,
  91158. configurable: true
  91159. });
  91160. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  91161. get: function () {
  91162. return this._gizmosEnabled.scaleGizmo;
  91163. },
  91164. /**
  91165. * If the scale gizmo is enabled
  91166. */
  91167. set: function (value) {
  91168. if (value) {
  91169. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  91170. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  91171. }
  91172. else if (this.gizmos.scaleGizmo) {
  91173. this.gizmos.scaleGizmo.attachedMesh = null;
  91174. }
  91175. this._gizmosEnabled.scaleGizmo = value;
  91176. },
  91177. enumerable: true,
  91178. configurable: true
  91179. });
  91180. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  91181. get: function () {
  91182. return this._gizmosEnabled.boundingBoxGizmo;
  91183. },
  91184. /**
  91185. * If the boundingBox gizmo is enabled
  91186. */
  91187. set: function (value) {
  91188. if (value) {
  91189. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  91190. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  91191. if (this._attachedMesh) {
  91192. this._attachedMesh.removeBehavior(this._dragBehavior);
  91193. this._attachedMesh.addBehavior(this._dragBehavior);
  91194. }
  91195. }
  91196. else if (this.gizmos.boundingBoxGizmo) {
  91197. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  91198. }
  91199. this._gizmosEnabled.boundingBoxGizmo = value;
  91200. },
  91201. enumerable: true,
  91202. configurable: true
  91203. });
  91204. /**
  91205. * Disposes of the gizmo manager
  91206. */
  91207. GizmoManager.prototype.dispose = function () {
  91208. this.scene.onPointerObservable.remove(this._pointerObserver);
  91209. for (var key in this.gizmos) {
  91210. var gizmo = (this.gizmos[key]);
  91211. if (gizmo) {
  91212. gizmo.dispose();
  91213. }
  91214. }
  91215. this._gizmoLayer.dispose();
  91216. };
  91217. return GizmoManager;
  91218. }());
  91219. BABYLON.GizmoManager = GizmoManager;
  91220. })(BABYLON || (BABYLON = {}));
  91221. //# sourceMappingURL=babylon.gizmoManager.js.map
  91222. var BABYLON;
  91223. (function (BABYLON) {
  91224. /**
  91225. * Defines a target to use with MorphTargetManager
  91226. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91227. */
  91228. var MorphTarget = /** @class */ (function () {
  91229. /**
  91230. * Creates a new MorphTarget
  91231. * @param name defines the name of the target
  91232. * @param influence defines the influence to use
  91233. */
  91234. function MorphTarget(
  91235. /** defines the name of the target */
  91236. name, influence, scene) {
  91237. if (influence === void 0) { influence = 0; }
  91238. if (scene === void 0) { scene = null; }
  91239. this.name = name;
  91240. /**
  91241. * Gets or sets the list of animations
  91242. */
  91243. this.animations = new Array();
  91244. this._positions = null;
  91245. this._normals = null;
  91246. this._tangents = null;
  91247. /**
  91248. * Observable raised when the influence changes
  91249. */
  91250. this.onInfluenceChanged = new BABYLON.Observable();
  91251. this._animationPropertiesOverride = null;
  91252. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91253. this.influence = influence;
  91254. }
  91255. Object.defineProperty(MorphTarget.prototype, "influence", {
  91256. /**
  91257. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  91258. */
  91259. get: function () {
  91260. return this._influence;
  91261. },
  91262. set: function (influence) {
  91263. if (this._influence === influence) {
  91264. return;
  91265. }
  91266. var previous = this._influence;
  91267. this._influence = influence;
  91268. if (this.onInfluenceChanged.hasObservers) {
  91269. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  91270. }
  91271. },
  91272. enumerable: true,
  91273. configurable: true
  91274. });
  91275. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  91276. /**
  91277. * Gets or sets the animation properties override
  91278. */
  91279. get: function () {
  91280. if (!this._animationPropertiesOverride && this._scene) {
  91281. return this._scene.animationPropertiesOverride;
  91282. }
  91283. return this._animationPropertiesOverride;
  91284. },
  91285. set: function (value) {
  91286. this._animationPropertiesOverride = value;
  91287. },
  91288. enumerable: true,
  91289. configurable: true
  91290. });
  91291. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  91292. /**
  91293. * Gets a boolean defining if the target contains position data
  91294. */
  91295. get: function () {
  91296. return !!this._positions;
  91297. },
  91298. enumerable: true,
  91299. configurable: true
  91300. });
  91301. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  91302. /**
  91303. * Gets a boolean defining if the target contains normal data
  91304. */
  91305. get: function () {
  91306. return !!this._normals;
  91307. },
  91308. enumerable: true,
  91309. configurable: true
  91310. });
  91311. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  91312. /**
  91313. * Gets a boolean defining if the target contains tangent data
  91314. */
  91315. get: function () {
  91316. return !!this._tangents;
  91317. },
  91318. enumerable: true,
  91319. configurable: true
  91320. });
  91321. /**
  91322. * Affects position data to this target
  91323. * @param data defines the position data to use
  91324. */
  91325. MorphTarget.prototype.setPositions = function (data) {
  91326. this._positions = data;
  91327. };
  91328. /**
  91329. * Gets the position data stored in this target
  91330. * @returns a FloatArray containing the position data (or null if not present)
  91331. */
  91332. MorphTarget.prototype.getPositions = function () {
  91333. return this._positions;
  91334. };
  91335. /**
  91336. * Affects normal data to this target
  91337. * @param data defines the normal data to use
  91338. */
  91339. MorphTarget.prototype.setNormals = function (data) {
  91340. this._normals = data;
  91341. };
  91342. /**
  91343. * Gets the normal data stored in this target
  91344. * @returns a FloatArray containing the normal data (or null if not present)
  91345. */
  91346. MorphTarget.prototype.getNormals = function () {
  91347. return this._normals;
  91348. };
  91349. /**
  91350. * Affects tangent data to this target
  91351. * @param data defines the tangent data to use
  91352. */
  91353. MorphTarget.prototype.setTangents = function (data) {
  91354. this._tangents = data;
  91355. };
  91356. /**
  91357. * Gets the tangent data stored in this target
  91358. * @returns a FloatArray containing the tangent data (or null if not present)
  91359. */
  91360. MorphTarget.prototype.getTangents = function () {
  91361. return this._tangents;
  91362. };
  91363. /**
  91364. * Serializes the current target into a Serialization object
  91365. * @returns the serialized object
  91366. */
  91367. MorphTarget.prototype.serialize = function () {
  91368. var serializationObject = {};
  91369. serializationObject.name = this.name;
  91370. serializationObject.influence = this.influence;
  91371. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  91372. if (this.hasNormals) {
  91373. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  91374. }
  91375. if (this.hasTangents) {
  91376. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  91377. }
  91378. // Animations
  91379. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  91380. return serializationObject;
  91381. };
  91382. // Statics
  91383. /**
  91384. * Creates a new target from serialized data
  91385. * @param serializationObject defines the serialized data to use
  91386. * @returns a new MorphTarget
  91387. */
  91388. MorphTarget.Parse = function (serializationObject) {
  91389. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  91390. result.setPositions(serializationObject.positions);
  91391. if (serializationObject.normals) {
  91392. result.setNormals(serializationObject.normals);
  91393. }
  91394. if (serializationObject.tangents) {
  91395. result.setTangents(serializationObject.tangents);
  91396. }
  91397. // Animations
  91398. if (serializationObject.animations) {
  91399. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  91400. var parsedAnimation = serializationObject.animations[animationIndex];
  91401. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  91402. }
  91403. }
  91404. return result;
  91405. };
  91406. /**
  91407. * Creates a MorphTarget from mesh data
  91408. * @param mesh defines the source mesh
  91409. * @param name defines the name to use for the new target
  91410. * @param influence defines the influence to attach to the target
  91411. * @returns a new MorphTarget
  91412. */
  91413. MorphTarget.FromMesh = function (mesh, name, influence) {
  91414. if (!name) {
  91415. name = mesh.name;
  91416. }
  91417. var result = new MorphTarget(name, influence, mesh.getScene());
  91418. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91419. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91420. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  91421. }
  91422. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  91423. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  91424. }
  91425. return result;
  91426. };
  91427. return MorphTarget;
  91428. }());
  91429. BABYLON.MorphTarget = MorphTarget;
  91430. })(BABYLON || (BABYLON = {}));
  91431. //# sourceMappingURL=babylon.morphTarget.js.map
  91432. var BABYLON;
  91433. (function (BABYLON) {
  91434. /**
  91435. * This class is used to deform meshes using morphing between different targets
  91436. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91437. */
  91438. var MorphTargetManager = /** @class */ (function () {
  91439. /**
  91440. * Creates a new MorphTargetManager
  91441. * @param scene defines the current scene
  91442. */
  91443. function MorphTargetManager(scene) {
  91444. if (scene === void 0) { scene = null; }
  91445. this._targets = new Array();
  91446. this._targetObservable = new Array();
  91447. this._activeTargets = new BABYLON.SmartArray(16);
  91448. this._supportsNormals = false;
  91449. this._supportsTangents = false;
  91450. this._vertexCount = 0;
  91451. this._uniqueId = 0;
  91452. this._tempInfluences = new Array();
  91453. if (!scene) {
  91454. scene = BABYLON.Engine.LastCreatedScene;
  91455. }
  91456. this._scene = scene;
  91457. if (this._scene) {
  91458. this._scene.morphTargetManagers.push(this);
  91459. this._uniqueId = this._scene.getUniqueId();
  91460. }
  91461. }
  91462. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  91463. /**
  91464. * Gets the unique ID of this manager
  91465. */
  91466. get: function () {
  91467. return this._uniqueId;
  91468. },
  91469. enumerable: true,
  91470. configurable: true
  91471. });
  91472. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  91473. /**
  91474. * Gets the number of vertices handled by this manager
  91475. */
  91476. get: function () {
  91477. return this._vertexCount;
  91478. },
  91479. enumerable: true,
  91480. configurable: true
  91481. });
  91482. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  91483. /**
  91484. * Gets a boolean indicating if this manager supports morphing of normals
  91485. */
  91486. get: function () {
  91487. return this._supportsNormals;
  91488. },
  91489. enumerable: true,
  91490. configurable: true
  91491. });
  91492. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  91493. /**
  91494. * Gets a boolean indicating if this manager supports morphing of tangents
  91495. */
  91496. get: function () {
  91497. return this._supportsTangents;
  91498. },
  91499. enumerable: true,
  91500. configurable: true
  91501. });
  91502. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  91503. /**
  91504. * Gets the number of targets stored in this manager
  91505. */
  91506. get: function () {
  91507. return this._targets.length;
  91508. },
  91509. enumerable: true,
  91510. configurable: true
  91511. });
  91512. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  91513. /**
  91514. * Gets the number of influencers (ie. the number of targets with influences > 0)
  91515. */
  91516. get: function () {
  91517. return this._activeTargets.length;
  91518. },
  91519. enumerable: true,
  91520. configurable: true
  91521. });
  91522. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  91523. /**
  91524. * Gets the list of influences (one per target)
  91525. */
  91526. get: function () {
  91527. return this._influences;
  91528. },
  91529. enumerable: true,
  91530. configurable: true
  91531. });
  91532. /**
  91533. * Gets the active target at specified index. An active target is a target with an influence > 0
  91534. * @param index defines the index to check
  91535. * @returns the requested target
  91536. */
  91537. MorphTargetManager.prototype.getActiveTarget = function (index) {
  91538. return this._activeTargets.data[index];
  91539. };
  91540. /**
  91541. * Gets the target at specified index
  91542. * @param index defines the index to check
  91543. * @returns the requested target
  91544. */
  91545. MorphTargetManager.prototype.getTarget = function (index) {
  91546. return this._targets[index];
  91547. };
  91548. /**
  91549. * Add a new target to this manager
  91550. * @param target defines the target to add
  91551. */
  91552. MorphTargetManager.prototype.addTarget = function (target) {
  91553. var _this = this;
  91554. this._targets.push(target);
  91555. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  91556. _this._syncActiveTargets(needUpdate);
  91557. }));
  91558. this._syncActiveTargets(true);
  91559. };
  91560. /**
  91561. * Removes a target from the manager
  91562. * @param target defines the target to remove
  91563. */
  91564. MorphTargetManager.prototype.removeTarget = function (target) {
  91565. var index = this._targets.indexOf(target);
  91566. if (index >= 0) {
  91567. this._targets.splice(index, 1);
  91568. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  91569. this._syncActiveTargets(true);
  91570. }
  91571. };
  91572. /**
  91573. * Serializes the current manager into a Serialization object
  91574. * @returns the serialized object
  91575. */
  91576. MorphTargetManager.prototype.serialize = function () {
  91577. var serializationObject = {};
  91578. serializationObject.id = this.uniqueId;
  91579. serializationObject.targets = [];
  91580. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91581. var target = _a[_i];
  91582. serializationObject.targets.push(target.serialize());
  91583. }
  91584. return serializationObject;
  91585. };
  91586. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  91587. var influenceCount = 0;
  91588. this._activeTargets.reset();
  91589. this._supportsNormals = true;
  91590. this._supportsTangents = true;
  91591. this._vertexCount = 0;
  91592. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91593. var target = _a[_i];
  91594. this._activeTargets.push(target);
  91595. this._tempInfluences[influenceCount++] = target.influence;
  91596. var positions = target.getPositions();
  91597. if (positions) {
  91598. this._supportsNormals = this._supportsNormals && target.hasNormals;
  91599. this._supportsTangents = this._supportsTangents && target.hasTangents;
  91600. var vertexCount = positions.length / 3;
  91601. if (this._vertexCount === 0) {
  91602. this._vertexCount = vertexCount;
  91603. }
  91604. else if (this._vertexCount !== vertexCount) {
  91605. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  91606. return;
  91607. }
  91608. }
  91609. }
  91610. if (!this._influences || this._influences.length !== influenceCount) {
  91611. this._influences = new Float32Array(influenceCount);
  91612. }
  91613. for (var index = 0; index < influenceCount; index++) {
  91614. this._influences[index] = this._tempInfluences[index];
  91615. }
  91616. if (needUpdate) {
  91617. this.synchronize();
  91618. }
  91619. };
  91620. /**
  91621. * Syncrhonize the targets with all the meshes using this morph target manager
  91622. */
  91623. MorphTargetManager.prototype.synchronize = function () {
  91624. if (!this._scene) {
  91625. return;
  91626. }
  91627. // Flag meshes as dirty to resync with the active targets
  91628. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  91629. var mesh = _a[_i];
  91630. if (mesh.morphTargetManager === this) {
  91631. mesh._syncGeometryWithMorphTargetManager();
  91632. }
  91633. }
  91634. };
  91635. // Statics
  91636. /**
  91637. * Creates a new MorphTargetManager from serialized data
  91638. * @param serializationObject defines the serialized data
  91639. * @param scene defines the hosting scene
  91640. * @returns the new MorphTargetManager
  91641. */
  91642. MorphTargetManager.Parse = function (serializationObject, scene) {
  91643. var result = new MorphTargetManager(scene);
  91644. result._uniqueId = serializationObject.id;
  91645. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  91646. var targetData = _a[_i];
  91647. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  91648. }
  91649. return result;
  91650. };
  91651. return MorphTargetManager;
  91652. }());
  91653. BABYLON.MorphTargetManager = MorphTargetManager;
  91654. })(BABYLON || (BABYLON = {}));
  91655. //# sourceMappingURL=babylon.morphTargetManager.js.map
  91656. var BABYLON;
  91657. (function (BABYLON) {
  91658. var Octree = /** @class */ (function () {
  91659. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  91660. if (maxDepth === void 0) { maxDepth = 2; }
  91661. this.maxDepth = maxDepth;
  91662. this.dynamicContent = new Array();
  91663. this._maxBlockCapacity = maxBlockCapacity || 64;
  91664. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  91665. this._creationFunc = creationFunc;
  91666. }
  91667. // Methods
  91668. Octree.prototype.update = function (worldMin, worldMax, entries) {
  91669. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  91670. };
  91671. Octree.prototype.addMesh = function (entry) {
  91672. for (var index = 0; index < this.blocks.length; index++) {
  91673. var block = this.blocks[index];
  91674. block.addEntry(entry);
  91675. }
  91676. };
  91677. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  91678. this._selectionContent.reset();
  91679. for (var index = 0; index < this.blocks.length; index++) {
  91680. var block = this.blocks[index];
  91681. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  91682. }
  91683. if (allowDuplicate) {
  91684. this._selectionContent.concat(this.dynamicContent);
  91685. }
  91686. else {
  91687. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91688. }
  91689. return this._selectionContent;
  91690. };
  91691. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  91692. this._selectionContent.reset();
  91693. for (var index = 0; index < this.blocks.length; index++) {
  91694. var block = this.blocks[index];
  91695. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91696. }
  91697. if (allowDuplicate) {
  91698. this._selectionContent.concat(this.dynamicContent);
  91699. }
  91700. else {
  91701. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91702. }
  91703. return this._selectionContent;
  91704. };
  91705. Octree.prototype.intersectsRay = function (ray) {
  91706. this._selectionContent.reset();
  91707. for (var index = 0; index < this.blocks.length; index++) {
  91708. var block = this.blocks[index];
  91709. block.intersectsRay(ray, this._selectionContent);
  91710. }
  91711. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91712. return this._selectionContent;
  91713. };
  91714. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91715. target.blocks = new Array();
  91716. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91717. // Segmenting space
  91718. for (var x = 0; x < 2; x++) {
  91719. for (var y = 0; y < 2; y++) {
  91720. for (var z = 0; z < 2; z++) {
  91721. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91722. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91723. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91724. block.addEntries(entries);
  91725. target.blocks.push(block);
  91726. }
  91727. }
  91728. }
  91729. };
  91730. Octree.CreationFuncForMeshes = function (entry, block) {
  91731. var boundingInfo = entry.getBoundingInfo();
  91732. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91733. block.entries.push(entry);
  91734. }
  91735. };
  91736. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91737. var boundingInfo = entry.getBoundingInfo();
  91738. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91739. block.entries.push(entry);
  91740. }
  91741. };
  91742. return Octree;
  91743. }());
  91744. BABYLON.Octree = Octree;
  91745. })(BABYLON || (BABYLON = {}));
  91746. //# sourceMappingURL=babylon.octree.js.map
  91747. var BABYLON;
  91748. (function (BABYLON) {
  91749. var OctreeBlock = /** @class */ (function () {
  91750. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91751. this.entries = new Array();
  91752. this._boundingVectors = new Array();
  91753. this._capacity = capacity;
  91754. this._depth = depth;
  91755. this._maxDepth = maxDepth;
  91756. this._creationFunc = creationFunc;
  91757. this._minPoint = minPoint;
  91758. this._maxPoint = maxPoint;
  91759. this._boundingVectors.push(minPoint.clone());
  91760. this._boundingVectors.push(maxPoint.clone());
  91761. this._boundingVectors.push(minPoint.clone());
  91762. this._boundingVectors[2].x = maxPoint.x;
  91763. this._boundingVectors.push(minPoint.clone());
  91764. this._boundingVectors[3].y = maxPoint.y;
  91765. this._boundingVectors.push(minPoint.clone());
  91766. this._boundingVectors[4].z = maxPoint.z;
  91767. this._boundingVectors.push(maxPoint.clone());
  91768. this._boundingVectors[5].z = minPoint.z;
  91769. this._boundingVectors.push(maxPoint.clone());
  91770. this._boundingVectors[6].x = minPoint.x;
  91771. this._boundingVectors.push(maxPoint.clone());
  91772. this._boundingVectors[7].y = minPoint.y;
  91773. }
  91774. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91775. // Property
  91776. get: function () {
  91777. return this._capacity;
  91778. },
  91779. enumerable: true,
  91780. configurable: true
  91781. });
  91782. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91783. get: function () {
  91784. return this._minPoint;
  91785. },
  91786. enumerable: true,
  91787. configurable: true
  91788. });
  91789. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91790. get: function () {
  91791. return this._maxPoint;
  91792. },
  91793. enumerable: true,
  91794. configurable: true
  91795. });
  91796. // Methods
  91797. OctreeBlock.prototype.addEntry = function (entry) {
  91798. if (this.blocks) {
  91799. for (var index = 0; index < this.blocks.length; index++) {
  91800. var block = this.blocks[index];
  91801. block.addEntry(entry);
  91802. }
  91803. return;
  91804. }
  91805. this._creationFunc(entry, this);
  91806. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91807. this.createInnerBlocks();
  91808. }
  91809. };
  91810. OctreeBlock.prototype.addEntries = function (entries) {
  91811. for (var index = 0; index < entries.length; index++) {
  91812. var mesh = entries[index];
  91813. this.addEntry(mesh);
  91814. }
  91815. };
  91816. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91817. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91818. if (this.blocks) {
  91819. for (var index = 0; index < this.blocks.length; index++) {
  91820. var block = this.blocks[index];
  91821. block.select(frustumPlanes, selection, allowDuplicate);
  91822. }
  91823. return;
  91824. }
  91825. if (allowDuplicate) {
  91826. selection.concat(this.entries);
  91827. }
  91828. else {
  91829. selection.concatWithNoDuplicate(this.entries);
  91830. }
  91831. }
  91832. };
  91833. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91834. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91835. if (this.blocks) {
  91836. for (var index = 0; index < this.blocks.length; index++) {
  91837. var block = this.blocks[index];
  91838. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91839. }
  91840. return;
  91841. }
  91842. if (allowDuplicate) {
  91843. selection.concat(this.entries);
  91844. }
  91845. else {
  91846. selection.concatWithNoDuplicate(this.entries);
  91847. }
  91848. }
  91849. };
  91850. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91851. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91852. if (this.blocks) {
  91853. for (var index = 0; index < this.blocks.length; index++) {
  91854. var block = this.blocks[index];
  91855. block.intersectsRay(ray, selection);
  91856. }
  91857. return;
  91858. }
  91859. selection.concatWithNoDuplicate(this.entries);
  91860. }
  91861. };
  91862. OctreeBlock.prototype.createInnerBlocks = function () {
  91863. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91864. };
  91865. return OctreeBlock;
  91866. }());
  91867. BABYLON.OctreeBlock = OctreeBlock;
  91868. })(BABYLON || (BABYLON = {}));
  91869. //# sourceMappingURL=babylon.octreeBlock.js.map
  91870. var BABYLON;
  91871. (function (BABYLON) {
  91872. /**
  91873. * Postprocess used to generate anaglyphic rendering
  91874. */
  91875. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91876. __extends(AnaglyphPostProcess, _super);
  91877. /**
  91878. * Creates a new AnaglyphPostProcess
  91879. * @param name defines postprocess name
  91880. * @param options defines creation options or target ratio scale
  91881. * @param rigCameras defines cameras using this postprocess
  91882. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91883. * @param engine defines hosting engine
  91884. * @param reusable defines if the postprocess will be reused multiple times per frame
  91885. */
  91886. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91887. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91888. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91889. _this.onApplyObservable.add(function (effect) {
  91890. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91891. });
  91892. return _this;
  91893. }
  91894. return AnaglyphPostProcess;
  91895. }(BABYLON.PostProcess));
  91896. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91897. })(BABYLON || (BABYLON = {}));
  91898. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91899. var BABYLON;
  91900. (function (BABYLON) {
  91901. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91902. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91903. });
  91904. /**
  91905. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91906. */
  91907. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91908. __extends(AnaglyphArcRotateCamera, _super);
  91909. /**
  91910. * Creates a new AnaglyphArcRotateCamera
  91911. * @param name defines camera name
  91912. * @param alpha defines alpha angle (in radians)
  91913. * @param beta defines beta angle (in radians)
  91914. * @param radius defines radius
  91915. * @param target defines camera target
  91916. * @param interaxialDistance defines distance between each color axis
  91917. * @param scene defines the hosting scene
  91918. */
  91919. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91920. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91921. _this.interaxialDistance = interaxialDistance;
  91922. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91923. return _this;
  91924. }
  91925. /**
  91926. * Gets camera class name
  91927. * @returns AnaglyphArcRotateCamera
  91928. */
  91929. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91930. return "AnaglyphArcRotateCamera";
  91931. };
  91932. return AnaglyphArcRotateCamera;
  91933. }(BABYLON.ArcRotateCamera));
  91934. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91935. })(BABYLON || (BABYLON = {}));
  91936. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  91937. var BABYLON;
  91938. (function (BABYLON) {
  91939. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  91940. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91941. });
  91942. /**
  91943. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91944. */
  91945. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91946. __extends(AnaglyphFreeCamera, _super);
  91947. /**
  91948. * Creates a new AnaglyphFreeCamera
  91949. * @param name defines camera name
  91950. * @param position defines initial position
  91951. * @param interaxialDistance defines distance between each color axis
  91952. * @param scene defines the hosting scene
  91953. */
  91954. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91955. var _this = _super.call(this, name, position, scene) || this;
  91956. _this.interaxialDistance = interaxialDistance;
  91957. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91958. return _this;
  91959. }
  91960. /**
  91961. * Gets camera class name
  91962. * @returns AnaglyphFreeCamera
  91963. */
  91964. AnaglyphFreeCamera.prototype.getClassName = function () {
  91965. return "AnaglyphFreeCamera";
  91966. };
  91967. return AnaglyphFreeCamera;
  91968. }(BABYLON.FreeCamera));
  91969. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91970. })(BABYLON || (BABYLON = {}));
  91971. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  91972. var BABYLON;
  91973. (function (BABYLON) {
  91974. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  91975. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91976. });
  91977. /**
  91978. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91979. */
  91980. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91981. __extends(AnaglyphGamepadCamera, _super);
  91982. /**
  91983. * Creates a new AnaglyphGamepadCamera
  91984. * @param name defines camera name
  91985. * @param position defines initial position
  91986. * @param interaxialDistance defines distance between each color axis
  91987. * @param scene defines the hosting scene
  91988. */
  91989. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91990. var _this = _super.call(this, name, position, scene) || this;
  91991. _this.interaxialDistance = interaxialDistance;
  91992. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91993. return _this;
  91994. }
  91995. /**
  91996. * Gets camera class name
  91997. * @returns AnaglyphGamepadCamera
  91998. */
  91999. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92000. return "AnaglyphGamepadCamera";
  92001. };
  92002. return AnaglyphGamepadCamera;
  92003. }(BABYLON.GamepadCamera));
  92004. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92005. })(BABYLON || (BABYLON = {}));
  92006. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  92007. var BABYLON;
  92008. (function (BABYLON) {
  92009. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  92010. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92011. });
  92012. /**
  92013. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92014. */
  92015. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92016. __extends(AnaglyphUniversalCamera, _super);
  92017. /**
  92018. * Creates a new AnaglyphUniversalCamera
  92019. * @param name defines camera name
  92020. * @param position defines initial position
  92021. * @param interaxialDistance defines distance between each color axis
  92022. * @param scene defines the hosting scene
  92023. */
  92024. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92025. var _this = _super.call(this, name, position, scene) || this;
  92026. _this.interaxialDistance = interaxialDistance;
  92027. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92028. return _this;
  92029. }
  92030. /**
  92031. * Gets camera class name
  92032. * @returns AnaglyphUniversalCamera
  92033. */
  92034. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92035. return "AnaglyphUniversalCamera";
  92036. };
  92037. return AnaglyphUniversalCamera;
  92038. }(BABYLON.UniversalCamera));
  92039. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92040. })(BABYLON || (BABYLON = {}));
  92041. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  92042. var BABYLON;
  92043. (function (BABYLON) {
  92044. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  92045. __extends(StereoscopicInterlacePostProcess, _super);
  92046. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  92047. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  92048. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92049. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92050. _this.onSizeChangedObservable.add(function () {
  92051. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92052. });
  92053. _this.onApplyObservable.add(function (effect) {
  92054. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  92055. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  92056. });
  92057. return _this;
  92058. }
  92059. return StereoscopicInterlacePostProcess;
  92060. }(BABYLON.PostProcess));
  92061. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  92062. })(BABYLON || (BABYLON = {}));
  92063. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  92064. var BABYLON;
  92065. (function (BABYLON) {
  92066. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  92067. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92068. });
  92069. /**
  92070. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92071. */
  92072. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92073. __extends(StereoscopicArcRotateCamera, _super);
  92074. /**
  92075. * Creates a new StereoscopicArcRotateCamera
  92076. * @param name defines camera name
  92077. * @param alpha defines alpha angle (in radians)
  92078. * @param beta defines beta angle (in radians)
  92079. * @param radius defines radius
  92080. * @param target defines camera target
  92081. * @param interaxialDistance defines distance between each color axis
  92082. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92083. * @param scene defines the hosting scene
  92084. */
  92085. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92086. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92087. _this.interaxialDistance = interaxialDistance;
  92088. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92089. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92090. return _this;
  92091. }
  92092. /**
  92093. * Gets camera class name
  92094. * @returns StereoscopicArcRotateCamera
  92095. */
  92096. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92097. return "StereoscopicArcRotateCamera";
  92098. };
  92099. return StereoscopicArcRotateCamera;
  92100. }(BABYLON.ArcRotateCamera));
  92101. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92102. })(BABYLON || (BABYLON = {}));
  92103. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  92104. var BABYLON;
  92105. (function (BABYLON) {
  92106. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92107. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92108. });
  92109. /**
  92110. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92111. */
  92112. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92113. __extends(StereoscopicFreeCamera, _super);
  92114. /**
  92115. * Creates a new StereoscopicFreeCamera
  92116. * @param name defines camera name
  92117. * @param position defines initial position
  92118. * @param interaxialDistance defines distance between each color axis
  92119. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92120. * @param scene defines the hosting scene
  92121. */
  92122. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92123. var _this = _super.call(this, name, position, scene) || this;
  92124. _this.interaxialDistance = interaxialDistance;
  92125. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92126. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92127. return _this;
  92128. }
  92129. /**
  92130. * Gets camera class name
  92131. * @returns StereoscopicFreeCamera
  92132. */
  92133. StereoscopicFreeCamera.prototype.getClassName = function () {
  92134. return "StereoscopicFreeCamera";
  92135. };
  92136. return StereoscopicFreeCamera;
  92137. }(BABYLON.FreeCamera));
  92138. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92139. })(BABYLON || (BABYLON = {}));
  92140. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  92141. var BABYLON;
  92142. (function (BABYLON) {
  92143. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  92144. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92145. });
  92146. /**
  92147. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92148. */
  92149. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92150. __extends(StereoscopicGamepadCamera, _super);
  92151. /**
  92152. * Creates a new StereoscopicGamepadCamera
  92153. * @param name defines camera name
  92154. * @param position defines initial position
  92155. * @param interaxialDistance defines distance between each color axis
  92156. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92157. * @param scene defines the hosting scene
  92158. */
  92159. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92160. var _this = _super.call(this, name, position, scene) || this;
  92161. _this.interaxialDistance = interaxialDistance;
  92162. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92163. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92164. return _this;
  92165. }
  92166. /**
  92167. * Gets camera class name
  92168. * @returns StereoscopicGamepadCamera
  92169. */
  92170. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92171. return "StereoscopicGamepadCamera";
  92172. };
  92173. return StereoscopicGamepadCamera;
  92174. }(BABYLON.GamepadCamera));
  92175. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92176. })(BABYLON || (BABYLON = {}));
  92177. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  92178. var BABYLON;
  92179. (function (BABYLON) {
  92180. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92181. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92182. });
  92183. /**
  92184. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92185. */
  92186. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92187. __extends(StereoscopicUniversalCamera, _super);
  92188. /**
  92189. * Creates a new StereoscopicUniversalCamera
  92190. * @param name defines camera name
  92191. * @param position defines initial position
  92192. * @param interaxialDistance defines distance between each color axis
  92193. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92194. * @param scene defines the hosting scene
  92195. */
  92196. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92197. var _this = _super.call(this, name, position, scene) || this;
  92198. _this.interaxialDistance = interaxialDistance;
  92199. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92200. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92201. return _this;
  92202. }
  92203. /**
  92204. * Gets camera class name
  92205. * @returns StereoscopicUniversalCamera
  92206. */
  92207. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92208. return "StereoscopicUniversalCamera";
  92209. };
  92210. return StereoscopicUniversalCamera;
  92211. }(BABYLON.UniversalCamera));
  92212. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92213. })(BABYLON || (BABYLON = {}));
  92214. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  92215. var BABYLON;
  92216. (function (BABYLON) {
  92217. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  92218. __extends(VRDistortionCorrectionPostProcess, _super);
  92219. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  92220. var _this = _super.call(this, name, "vrDistortionCorrection", [
  92221. 'LensCenter',
  92222. 'Scale',
  92223. 'ScaleIn',
  92224. 'HmdWarpParam'
  92225. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  92226. _this._isRightEye = isRightEye;
  92227. _this._distortionFactors = vrMetrics.distortionK;
  92228. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  92229. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  92230. _this.adaptScaleToCurrentViewport = true;
  92231. _this.onSizeChangedObservable.add(function () {
  92232. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  92233. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  92234. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  92235. });
  92236. _this.onApplyObservable.add(function (effect) {
  92237. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  92238. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  92239. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  92240. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  92241. });
  92242. return _this;
  92243. }
  92244. return VRDistortionCorrectionPostProcess;
  92245. }(BABYLON.PostProcess));
  92246. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  92247. })(BABYLON || (BABYLON = {}));
  92248. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  92249. var BABYLON;
  92250. (function (BABYLON) {
  92251. /**
  92252. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  92253. * Screen rotation is taken into account.
  92254. */
  92255. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  92256. function FreeCameraDeviceOrientationInput() {
  92257. var _this = this;
  92258. this._screenOrientationAngle = 0;
  92259. this._screenQuaternion = new BABYLON.Quaternion();
  92260. this._alpha = 0;
  92261. this._beta = 0;
  92262. this._gamma = 0;
  92263. this._orientationChanged = function () {
  92264. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  92265. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  92266. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  92267. };
  92268. this._deviceOrientation = function (evt) {
  92269. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  92270. _this._beta = evt.beta !== null ? evt.beta : 0;
  92271. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  92272. };
  92273. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  92274. this._orientationChanged();
  92275. }
  92276. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  92277. get: function () {
  92278. return this._camera;
  92279. },
  92280. set: function (camera) {
  92281. this._camera = camera;
  92282. if (this._camera != null && !this._camera.rotationQuaternion) {
  92283. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  92284. }
  92285. },
  92286. enumerable: true,
  92287. configurable: true
  92288. });
  92289. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92290. window.addEventListener("orientationchange", this._orientationChanged);
  92291. window.addEventListener("deviceorientation", this._deviceOrientation);
  92292. //In certain cases, the attach control is called AFTER orientation was changed,
  92293. //So this is needed.
  92294. this._orientationChanged();
  92295. };
  92296. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  92297. window.removeEventListener("orientationchange", this._orientationChanged);
  92298. window.removeEventListener("deviceorientation", this._deviceOrientation);
  92299. };
  92300. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  92301. //if no device orientation provided, don't update the rotation.
  92302. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  92303. if (!this._alpha)
  92304. return;
  92305. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  92306. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  92307. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  92308. //Mirror on XY Plane
  92309. this._camera.rotationQuaternion.z *= -1;
  92310. this._camera.rotationQuaternion.w *= -1;
  92311. };
  92312. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  92313. return "FreeCameraDeviceOrientationInput";
  92314. };
  92315. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  92316. return "deviceOrientation";
  92317. };
  92318. return FreeCameraDeviceOrientationInput;
  92319. }());
  92320. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  92321. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  92322. })(BABYLON || (BABYLON = {}));
  92323. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  92324. var BABYLON;
  92325. (function (BABYLON) {
  92326. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  92327. function ArcRotateCameraVRDeviceOrientationInput() {
  92328. this.alphaCorrection = 1;
  92329. this.betaCorrection = 1;
  92330. this.gammaCorrection = 1;
  92331. this._alpha = 0;
  92332. this._gamma = 0;
  92333. this._dirty = false;
  92334. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  92335. }
  92336. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92337. this.camera.attachControl(element, noPreventDefault);
  92338. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  92339. };
  92340. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  92341. if (evt.alpha !== null) {
  92342. this._alpha = +evt.alpha | 0;
  92343. }
  92344. if (evt.gamma !== null) {
  92345. this._gamma = +evt.gamma | 0;
  92346. }
  92347. this._dirty = true;
  92348. };
  92349. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  92350. if (this._dirty) {
  92351. this._dirty = false;
  92352. if (this._gamma < 0) {
  92353. this._gamma = 180 + this._gamma;
  92354. }
  92355. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  92356. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  92357. }
  92358. };
  92359. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  92360. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  92361. };
  92362. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  92363. return "ArcRotateCameraVRDeviceOrientationInput";
  92364. };
  92365. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  92366. return "VRDeviceOrientation";
  92367. };
  92368. return ArcRotateCameraVRDeviceOrientationInput;
  92369. }());
  92370. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  92371. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  92372. })(BABYLON || (BABYLON = {}));
  92373. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  92374. var BABYLON;
  92375. (function (BABYLON) {
  92376. var VRCameraMetrics = /** @class */ (function () {
  92377. function VRCameraMetrics() {
  92378. this.compensateDistortion = true;
  92379. }
  92380. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  92381. get: function () {
  92382. return this.hResolution / (2 * this.vResolution);
  92383. },
  92384. enumerable: true,
  92385. configurable: true
  92386. });
  92387. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  92388. get: function () {
  92389. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  92390. },
  92391. enumerable: true,
  92392. configurable: true
  92393. });
  92394. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  92395. get: function () {
  92396. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92397. var h = (4 * meters) / this.hScreenSize;
  92398. return BABYLON.Matrix.Translation(h, 0, 0);
  92399. },
  92400. enumerable: true,
  92401. configurable: true
  92402. });
  92403. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  92404. get: function () {
  92405. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92406. var h = (4 * meters) / this.hScreenSize;
  92407. return BABYLON.Matrix.Translation(-h, 0, 0);
  92408. },
  92409. enumerable: true,
  92410. configurable: true
  92411. });
  92412. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  92413. get: function () {
  92414. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  92415. },
  92416. enumerable: true,
  92417. configurable: true
  92418. });
  92419. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  92420. get: function () {
  92421. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  92422. },
  92423. enumerable: true,
  92424. configurable: true
  92425. });
  92426. VRCameraMetrics.GetDefault = function () {
  92427. var result = new VRCameraMetrics();
  92428. result.hResolution = 1280;
  92429. result.vResolution = 800;
  92430. result.hScreenSize = 0.149759993;
  92431. result.vScreenSize = 0.0935999975;
  92432. result.vScreenCenter = 0.0467999987;
  92433. result.eyeToScreenDistance = 0.0410000011;
  92434. result.lensSeparationDistance = 0.0635000020;
  92435. result.interpupillaryDistance = 0.0640000030;
  92436. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  92437. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  92438. result.postProcessScaleFactor = 1.714605507808412;
  92439. result.lensCenterOffset = 0.151976421;
  92440. return result;
  92441. };
  92442. return VRCameraMetrics;
  92443. }());
  92444. BABYLON.VRCameraMetrics = VRCameraMetrics;
  92445. })(BABYLON || (BABYLON = {}));
  92446. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  92447. var BABYLON;
  92448. (function (BABYLON) {
  92449. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  92450. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92451. });
  92452. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  92453. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92454. });
  92455. /**
  92456. * This represents a WebVR camera.
  92457. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  92458. * @example http://doc.babylonjs.com/how_to/webvr_camera
  92459. */
  92460. var WebVRFreeCamera = /** @class */ (function (_super) {
  92461. __extends(WebVRFreeCamera, _super);
  92462. /**
  92463. * Instantiates a WebVRFreeCamera.
  92464. * @param name The name of the WebVRFreeCamera
  92465. * @param position The starting anchor position for the camera
  92466. * @param scene The scene the camera belongs to
  92467. * @param webVROptions a set of customizable options for the webVRCamera
  92468. */
  92469. function WebVRFreeCamera(name, position, scene, webVROptions) {
  92470. if (webVROptions === void 0) { webVROptions = {}; }
  92471. var _this = _super.call(this, name, position, scene) || this;
  92472. _this.webVROptions = webVROptions;
  92473. /**
  92474. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  92475. */
  92476. _this._vrDevice = null;
  92477. /**
  92478. * The rawPose of the vrDevice.
  92479. */
  92480. _this.rawPose = null;
  92481. _this._specsVersion = "1.1";
  92482. _this._attached = false;
  92483. _this._descendants = [];
  92484. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  92485. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  92486. /** @hidden */
  92487. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  92488. _this._standingMatrix = null;
  92489. /**
  92490. * Represents device position in babylon space.
  92491. */
  92492. _this.devicePosition = BABYLON.Vector3.Zero();
  92493. /**
  92494. * Represents device rotation in babylon space.
  92495. */
  92496. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  92497. /**
  92498. * The scale of the device to be used when translating from device space to babylon space.
  92499. */
  92500. _this.deviceScaleFactor = 1;
  92501. _this._deviceToWorld = BABYLON.Matrix.Identity();
  92502. _this._worldToDevice = BABYLON.Matrix.Identity();
  92503. /**
  92504. * References to the webVR controllers for the vrDevice.
  92505. */
  92506. _this.controllers = [];
  92507. /**
  92508. * Emits an event when a controller is attached.
  92509. */
  92510. _this.onControllersAttachedObservable = new BABYLON.Observable();
  92511. /**
  92512. * Emits an event when a controller's mesh has been loaded;
  92513. */
  92514. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92515. /**
  92516. * Emits an event when the HMD's pose has been updated.
  92517. */
  92518. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  92519. _this._poseSet = false;
  92520. /**
  92521. * If the rig cameras be used as parent instead of this camera.
  92522. */
  92523. _this.rigParenting = true;
  92524. _this._defaultHeight = undefined;
  92525. _this._workingVector = BABYLON.Vector3.Zero();
  92526. _this._oneVector = BABYLON.Vector3.One();
  92527. _this._workingMatrix = BABYLON.Matrix.Identity();
  92528. _this._cache.position = BABYLON.Vector3.Zero();
  92529. if (webVROptions.defaultHeight) {
  92530. _this._defaultHeight = webVROptions.defaultHeight;
  92531. _this.position.y = _this._defaultHeight;
  92532. }
  92533. _this.minZ = 0.1;
  92534. //legacy support - the compensation boolean was removed.
  92535. if (arguments.length === 5) {
  92536. _this.webVROptions = arguments[4];
  92537. }
  92538. // default webVR options
  92539. if (_this.webVROptions.trackPosition == undefined) {
  92540. _this.webVROptions.trackPosition = true;
  92541. }
  92542. if (_this.webVROptions.controllerMeshes == undefined) {
  92543. _this.webVROptions.controllerMeshes = true;
  92544. }
  92545. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  92546. _this.webVROptions.defaultLightingOnControllers = true;
  92547. }
  92548. _this.rotationQuaternion = new BABYLON.Quaternion();
  92549. if (_this.webVROptions && _this.webVROptions.positionScale) {
  92550. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  92551. }
  92552. //enable VR
  92553. var engine = _this.getEngine();
  92554. _this._onVREnabled = function (success) { if (success) {
  92555. _this.initControllers();
  92556. } };
  92557. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  92558. engine.initWebVR().add(function (event) {
  92559. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  92560. return;
  92561. }
  92562. _this._vrDevice = event.vrDisplay;
  92563. //reset the rig parameters.
  92564. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  92565. if (_this._attached) {
  92566. _this.getEngine().enableVR();
  92567. }
  92568. });
  92569. if (typeof (VRFrameData) !== "undefined")
  92570. _this._frameData = new VRFrameData();
  92571. /**
  92572. * The idea behind the following lines:
  92573. * objects that have the camera as parent should actually have the rig cameras as a parent.
  92574. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  92575. * the second will not show it correctly.
  92576. *
  92577. * To solve this - each object that has the camera as parent will be added to a protected array.
  92578. * When the rig camera renders, it will take this array and set all of those to be its children.
  92579. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  92580. * Amazing!
  92581. */
  92582. scene.onBeforeCameraRenderObservable.add(function (camera) {
  92583. if (camera.parent === _this && _this.rigParenting) {
  92584. _this._descendants = _this.getDescendants(true, function (n) {
  92585. // don't take the cameras or the controllers!
  92586. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  92587. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  92588. return !isController && !isRigCamera;
  92589. });
  92590. _this._descendants.forEach(function (node) {
  92591. node.parent = camera;
  92592. });
  92593. }
  92594. });
  92595. scene.onAfterCameraRenderObservable.add(function (camera) {
  92596. if (camera.parent === _this && _this.rigParenting) {
  92597. _this._descendants.forEach(function (node) {
  92598. node.parent = _this;
  92599. });
  92600. }
  92601. });
  92602. return _this;
  92603. }
  92604. /**
  92605. * Gets the device distance from the ground in meters.
  92606. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  92607. */
  92608. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  92609. if (this._standingMatrix) {
  92610. // Add standing matrix offset to get real offset from ground in room
  92611. this._standingMatrix.getTranslationToRef(this._workingVector);
  92612. return this._deviceRoomPosition.y + this._workingVector.y;
  92613. }
  92614. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  92615. return this._defaultHeight || 0;
  92616. };
  92617. /**
  92618. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92619. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  92620. */
  92621. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  92622. var _this = this;
  92623. if (callback === void 0) { callback = function (bool) { }; }
  92624. // Use standing matrix if available
  92625. this.getEngine().initWebVRAsync().then(function (result) {
  92626. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  92627. callback(false);
  92628. }
  92629. else {
  92630. _this._standingMatrix = new BABYLON.Matrix();
  92631. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  92632. if (!_this.getScene().useRightHandedSystem) {
  92633. [2, 6, 8, 9, 14].forEach(function (num) {
  92634. if (_this._standingMatrix) {
  92635. _this._standingMatrix.m[num] *= -1;
  92636. }
  92637. });
  92638. }
  92639. callback(true);
  92640. }
  92641. });
  92642. };
  92643. /**
  92644. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92645. * @returns A promise with a boolean set to if the standing matrix is supported.
  92646. */
  92647. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  92648. var _this = this;
  92649. return new Promise(function (res, rej) {
  92650. _this.useStandingMatrix(function (supported) {
  92651. res(supported);
  92652. });
  92653. });
  92654. };
  92655. /**
  92656. * Disposes the camera
  92657. */
  92658. WebVRFreeCamera.prototype.dispose = function () {
  92659. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  92660. _super.prototype.dispose.call(this);
  92661. };
  92662. /**
  92663. * Gets a vrController by name.
  92664. * @param name The name of the controller to retreive
  92665. * @returns the controller matching the name specified or null if not found
  92666. */
  92667. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  92668. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  92669. var gp = _a[_i];
  92670. if (gp.hand === name) {
  92671. return gp;
  92672. }
  92673. }
  92674. return null;
  92675. };
  92676. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  92677. /**
  92678. * The controller corrisponding to the users left hand.
  92679. */
  92680. get: function () {
  92681. if (!this._leftController) {
  92682. this._leftController = this.getControllerByName("left");
  92683. }
  92684. return this._leftController;
  92685. },
  92686. enumerable: true,
  92687. configurable: true
  92688. });
  92689. ;
  92690. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  92691. /**
  92692. * The controller corrisponding to the users right hand.
  92693. */
  92694. get: function () {
  92695. if (!this._rightController) {
  92696. this._rightController = this.getControllerByName("right");
  92697. }
  92698. return this._rightController;
  92699. },
  92700. enumerable: true,
  92701. configurable: true
  92702. });
  92703. ;
  92704. /**
  92705. * Casts a ray forward from the vrCamera's gaze.
  92706. * @param length Length of the ray (default: 100)
  92707. * @returns the ray corrisponding to the gaze
  92708. */
  92709. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  92710. if (length === void 0) { length = 100; }
  92711. if (this.leftCamera) {
  92712. // Use left eye to avoid computation to compute center on every call
  92713. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  92714. }
  92715. else {
  92716. return _super.prototype.getForwardRay.call(this, length);
  92717. }
  92718. };
  92719. /**
  92720. * Updates the camera based on device's frame data
  92721. */
  92722. WebVRFreeCamera.prototype._checkInputs = function () {
  92723. if (this._vrDevice && this._vrDevice.isPresenting) {
  92724. this._vrDevice.getFrameData(this._frameData);
  92725. this.updateFromDevice(this._frameData.pose);
  92726. }
  92727. _super.prototype._checkInputs.call(this);
  92728. };
  92729. /**
  92730. * Updates the poseControlled values based on the input device pose.
  92731. * @param poseData Pose coming from the device
  92732. */
  92733. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  92734. if (poseData && poseData.orientation) {
  92735. this.rawPose = poseData;
  92736. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  92737. if (this.getScene().useRightHandedSystem) {
  92738. this._deviceRoomRotationQuaternion.z *= -1;
  92739. this._deviceRoomRotationQuaternion.w *= -1;
  92740. }
  92741. if (this.webVROptions.trackPosition && this.rawPose.position) {
  92742. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  92743. if (this.getScene().useRightHandedSystem) {
  92744. this._deviceRoomPosition.z *= -1;
  92745. }
  92746. }
  92747. this._poseSet = true;
  92748. }
  92749. };
  92750. /**
  92751. * WebVR's attach control will start broadcasting frames to the device.
  92752. * Note that in certain browsers (chrome for example) this function must be called
  92753. * within a user-interaction callback. Example:
  92754. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  92755. *
  92756. * @param element html element to attach the vrDevice to
  92757. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  92758. */
  92759. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  92760. _super.prototype.attachControl.call(this, element, noPreventDefault);
  92761. this._attached = true;
  92762. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  92763. if (this._vrDevice) {
  92764. this.getEngine().enableVR();
  92765. }
  92766. };
  92767. /**
  92768. * Detaches the camera from the html element and disables VR
  92769. *
  92770. * @param element html element to detach from
  92771. */
  92772. WebVRFreeCamera.prototype.detachControl = function (element) {
  92773. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  92774. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  92775. _super.prototype.detachControl.call(this, element);
  92776. this._attached = false;
  92777. this.getEngine().disableVR();
  92778. };
  92779. /**
  92780. * @returns the name of this class
  92781. */
  92782. WebVRFreeCamera.prototype.getClassName = function () {
  92783. return "WebVRFreeCamera";
  92784. };
  92785. /**
  92786. * Calls resetPose on the vrDisplay
  92787. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  92788. */
  92789. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  92790. //uses the vrDisplay's "resetPose()".
  92791. //pitch and roll won't be affected.
  92792. this._vrDevice.resetPose();
  92793. };
  92794. /**
  92795. * Updates the rig cameras (left and right eye)
  92796. */
  92797. WebVRFreeCamera.prototype._updateRigCameras = function () {
  92798. var camLeft = this._rigCameras[0];
  92799. var camRight = this._rigCameras[1];
  92800. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92801. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92802. camLeft.position.copyFrom(this._deviceRoomPosition);
  92803. camRight.position.copyFrom(this._deviceRoomPosition);
  92804. };
  92805. /**
  92806. * Updates the cached values of the camera
  92807. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  92808. */
  92809. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  92810. var _this = this;
  92811. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  92812. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  92813. if (!this.updateCacheCalled) {
  92814. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  92815. this.updateCacheCalled = true;
  92816. this.update();
  92817. }
  92818. // Set working vector to the device position in room space rotated by the new rotation
  92819. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  92820. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  92821. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92822. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92823. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92824. // Add translation from anchor position
  92825. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92826. this._workingVector.addInPlace(this.position);
  92827. this._workingVector.subtractInPlace(this._cache.position);
  92828. this._deviceToWorld.setTranslation(this._workingVector);
  92829. // Set an inverted matrix to be used when updating the camera
  92830. this._deviceToWorld.invertToRef(this._worldToDevice);
  92831. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92832. this.controllers.forEach(function (controller) {
  92833. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92834. controller.update();
  92835. });
  92836. }
  92837. if (!ignoreParentClass) {
  92838. _super.prototype._updateCache.call(this);
  92839. }
  92840. this.updateCacheCalled = false;
  92841. };
  92842. /**
  92843. * Updates the current device position and rotation in the babylon world
  92844. */
  92845. WebVRFreeCamera.prototype.update = function () {
  92846. // Get current device position in babylon world
  92847. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  92848. // Get current device rotation in babylon world
  92849. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  92850. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  92851. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  92852. if (this._poseSet) {
  92853. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  92854. }
  92855. _super.prototype.update.call(this);
  92856. };
  92857. /**
  92858. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  92859. * @returns an identity matrix
  92860. */
  92861. WebVRFreeCamera.prototype._getViewMatrix = function () {
  92862. return BABYLON.Matrix.Identity();
  92863. };
  92864. /**
  92865. * This function is called by the two RIG cameras.
  92866. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  92867. */
  92868. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  92869. var _this = this;
  92870. // Update the parent camera prior to using a child camera to avoid desynchronization
  92871. var parentCamera = this._cameraRigParams["parentCamera"];
  92872. parentCamera._updateCache();
  92873. //WebVR 1.1
  92874. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  92875. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  92876. if (!this.getScene().useRightHandedSystem) {
  92877. [2, 6, 8, 9, 14].forEach(function (num) {
  92878. _this._webvrViewMatrix.m[num] *= -1;
  92879. });
  92880. }
  92881. // update the camera rotation matrix
  92882. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  92883. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  92884. // Computing target and final matrix
  92885. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  92886. // should the view matrix be updated with scale and position offset?
  92887. if (parentCamera.deviceScaleFactor !== 1) {
  92888. this._webvrViewMatrix.invert();
  92889. // scale the position, if set
  92890. if (parentCamera.deviceScaleFactor) {
  92891. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  92892. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  92893. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  92894. }
  92895. this._webvrViewMatrix.invert();
  92896. }
  92897. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  92898. // Compute global position
  92899. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  92900. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  92901. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  92902. this._workingMatrix.getTranslationToRef(this._globalPosition);
  92903. this._markSyncedWithParent();
  92904. return this._webvrViewMatrix;
  92905. };
  92906. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  92907. var _this = this;
  92908. var parentCamera = this.parent;
  92909. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  92910. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  92911. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  92912. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  92913. //babylon compatible matrix
  92914. if (!this.getScene().useRightHandedSystem) {
  92915. [8, 9, 10, 11].forEach(function (num) {
  92916. _this._projectionMatrix.m[num] *= -1;
  92917. });
  92918. }
  92919. return this._projectionMatrix;
  92920. };
  92921. /**
  92922. * Initializes the controllers and their meshes
  92923. */
  92924. WebVRFreeCamera.prototype.initControllers = function () {
  92925. var _this = this;
  92926. this.controllers = [];
  92927. var manager = this.getScene().gamepadManager;
  92928. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  92929. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92930. var webVrController = gamepad;
  92931. if (webVrController.defaultModel) {
  92932. webVrController.defaultModel.setEnabled(false);
  92933. }
  92934. if (webVrController.hand === "right") {
  92935. _this._rightController = null;
  92936. }
  92937. if (webVrController.hand === "left") {
  92938. _this._leftController = null;
  92939. }
  92940. var controllerIndex = _this.controllers.indexOf(webVrController);
  92941. if (controllerIndex !== -1) {
  92942. _this.controllers.splice(controllerIndex, 1);
  92943. }
  92944. }
  92945. });
  92946. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  92947. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92948. var webVrController_1 = gamepad;
  92949. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  92950. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  92951. if (_this.webVROptions.controllerMeshes) {
  92952. if (webVrController_1.defaultModel) {
  92953. webVrController_1.defaultModel.setEnabled(true);
  92954. }
  92955. else {
  92956. // Load the meshes
  92957. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  92958. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  92959. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  92960. if (_this.webVROptions.defaultLightingOnControllers) {
  92961. if (!_this._lightOnControllers) {
  92962. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  92963. }
  92964. var activateLightOnSubMeshes_1 = function (mesh, light) {
  92965. var children = mesh.getChildren();
  92966. if (children.length !== 0) {
  92967. children.forEach(function (mesh) {
  92968. light.includedOnlyMeshes.push(mesh);
  92969. activateLightOnSubMeshes_1(mesh, light);
  92970. });
  92971. }
  92972. };
  92973. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  92974. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  92975. }
  92976. });
  92977. }
  92978. }
  92979. webVrController_1.attachToPoseControlledCamera(_this);
  92980. // since this is async - sanity check. Is the controller already stored?
  92981. if (_this.controllers.indexOf(webVrController_1) === -1) {
  92982. //add to the controllers array
  92983. _this.controllers.push(webVrController_1);
  92984. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  92985. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  92986. // So we're overriding setting left & right manually to be sure
  92987. var firstViveWandDetected = false;
  92988. for (var i = 0; i < _this.controllers.length; i++) {
  92989. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92990. if (!firstViveWandDetected) {
  92991. firstViveWandDetected = true;
  92992. _this.controllers[i].hand = "left";
  92993. }
  92994. else {
  92995. _this.controllers[i].hand = "right";
  92996. }
  92997. }
  92998. }
  92999. //did we find enough controllers? Great! let the developer know.
  93000. if (_this.controllers.length >= 2) {
  93001. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  93002. }
  93003. }
  93004. }
  93005. });
  93006. };
  93007. return WebVRFreeCamera;
  93008. }(BABYLON.FreeCamera));
  93009. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  93010. })(BABYLON || (BABYLON = {}));
  93011. //# sourceMappingURL=babylon.webVRCamera.js.map
  93012. var BABYLON;
  93013. (function (BABYLON) {
  93014. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  93015. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  93016. });
  93017. // We're mainly based on the logic defined into the FreeCamera code
  93018. /**
  93019. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  93020. * being tilted forward or back and left or right.
  93021. */
  93022. var DeviceOrientationCamera = /** @class */ (function (_super) {
  93023. __extends(DeviceOrientationCamera, _super);
  93024. /**
  93025. * Creates a new device orientation camera
  93026. * @param name The name of the camera
  93027. * @param position The start position camera
  93028. * @param scene The scene the camera belongs to
  93029. */
  93030. function DeviceOrientationCamera(name, position, scene) {
  93031. var _this = _super.call(this, name, position, scene) || this;
  93032. _this._quaternionCache = new BABYLON.Quaternion();
  93033. _this.inputs.addDeviceOrientation();
  93034. return _this;
  93035. }
  93036. /**
  93037. * Gets the current instance class name ("DeviceOrientationCamera").
  93038. * This helps avoiding instanceof at run time.
  93039. * @returns the class name
  93040. */
  93041. DeviceOrientationCamera.prototype.getClassName = function () {
  93042. return "DeviceOrientationCamera";
  93043. };
  93044. /**
  93045. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  93046. */
  93047. DeviceOrientationCamera.prototype._checkInputs = function () {
  93048. _super.prototype._checkInputs.call(this);
  93049. this._quaternionCache.copyFrom(this.rotationQuaternion);
  93050. if (this._initialQuaternion) {
  93051. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93052. }
  93053. };
  93054. /**
  93055. * Reset the camera to its default orientation on the specified axis only.
  93056. * @param axis The axis to reset
  93057. */
  93058. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  93059. var _this = this;
  93060. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  93061. //can only work if this camera has a rotation quaternion already.
  93062. if (!this.rotationQuaternion)
  93063. return;
  93064. if (!this._initialQuaternion) {
  93065. this._initialQuaternion = new BABYLON.Quaternion();
  93066. }
  93067. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  93068. ['x', 'y', 'z'].forEach(function (axisName) {
  93069. if (!axis[axisName]) {
  93070. _this._initialQuaternion[axisName] = 0;
  93071. }
  93072. else {
  93073. _this._initialQuaternion[axisName] *= -1;
  93074. }
  93075. });
  93076. this._initialQuaternion.normalize();
  93077. //force rotation update
  93078. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93079. };
  93080. return DeviceOrientationCamera;
  93081. }(BABYLON.FreeCamera));
  93082. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  93083. })(BABYLON || (BABYLON = {}));
  93084. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  93085. var BABYLON;
  93086. (function (BABYLON) {
  93087. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93088. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93089. });
  93090. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  93091. __extends(VRDeviceOrientationFreeCamera, _super);
  93092. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93093. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93094. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93095. var _this = _super.call(this, name, position, scene) || this;
  93096. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93097. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93098. return _this;
  93099. }
  93100. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  93101. return "VRDeviceOrientationFreeCamera";
  93102. };
  93103. return VRDeviceOrientationFreeCamera;
  93104. }(BABYLON.DeviceOrientationCamera));
  93105. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  93106. })(BABYLON || (BABYLON = {}));
  93107. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  93108. var BABYLON;
  93109. (function (BABYLON) {
  93110. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93111. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  93112. });
  93113. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  93114. __extends(VRDeviceOrientationArcRotateCamera, _super);
  93115. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  93116. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93117. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93118. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93119. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93120. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93121. _this.inputs.addVRDeviceOrientation();
  93122. return _this;
  93123. }
  93124. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  93125. return "VRDeviceOrientationArcRotateCamera";
  93126. };
  93127. return VRDeviceOrientationArcRotateCamera;
  93128. }(BABYLON.ArcRotateCamera));
  93129. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  93130. })(BABYLON || (BABYLON = {}));
  93131. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  93132. var BABYLON;
  93133. (function (BABYLON) {
  93134. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  93135. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  93136. });
  93137. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  93138. __extends(VRDeviceOrientationGamepadCamera, _super);
  93139. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93140. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93141. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93142. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  93143. _this.inputs.addGamepad();
  93144. return _this;
  93145. }
  93146. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  93147. return "VRDeviceOrientationGamepadCamera";
  93148. };
  93149. return VRDeviceOrientationGamepadCamera;
  93150. }(BABYLON.VRDeviceOrientationFreeCamera));
  93151. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  93152. })(BABYLON || (BABYLON = {}));
  93153. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  93154. var BABYLON;
  93155. (function (BABYLON) {
  93156. var VRExperienceHelperGazer = /** @class */ (function () {
  93157. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  93158. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  93159. this.scene = scene;
  93160. this._pointerDownOnMeshAsked = false;
  93161. this._isActionableMesh = false;
  93162. this._teleportationRequestInitiated = false;
  93163. this._teleportationBackRequestInitiated = false;
  93164. this._rotationRightAsked = false;
  93165. this._rotationLeftAsked = false;
  93166. this._dpadPressed = true;
  93167. this._activePointer = false;
  93168. this._id = VRExperienceHelperGazer._idCounter++;
  93169. // Gaze tracker
  93170. if (!gazeTrackerToClone) {
  93171. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  93172. this._gazeTracker.bakeCurrentTransformIntoVertices();
  93173. this._gazeTracker.isPickable = false;
  93174. this._gazeTracker.isVisible = false;
  93175. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  93176. targetMat.specularColor = BABYLON.Color3.Black();
  93177. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93178. targetMat.backFaceCulling = false;
  93179. this._gazeTracker.material = targetMat;
  93180. }
  93181. else {
  93182. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  93183. }
  93184. }
  93185. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  93186. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  93187. };
  93188. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  93189. this._pointerDownOnMeshAsked = true;
  93190. if (this._currentHit) {
  93191. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  93192. }
  93193. };
  93194. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  93195. if (this._currentHit) {
  93196. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  93197. }
  93198. this._pointerDownOnMeshAsked = false;
  93199. };
  93200. VRExperienceHelperGazer.prototype._activatePointer = function () {
  93201. this._activePointer = true;
  93202. };
  93203. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  93204. this._activePointer = false;
  93205. };
  93206. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  93207. if (distance === void 0) { distance = 100; }
  93208. };
  93209. VRExperienceHelperGazer.prototype.dispose = function () {
  93210. this._interactionsEnabled = false;
  93211. this._teleportationEnabled = false;
  93212. if (this._gazeTracker) {
  93213. this._gazeTracker.dispose();
  93214. }
  93215. };
  93216. VRExperienceHelperGazer._idCounter = 0;
  93217. return VRExperienceHelperGazer;
  93218. }());
  93219. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  93220. __extends(VRExperienceHelperControllerGazer, _super);
  93221. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  93222. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  93223. _this.webVRController = webVRController;
  93224. // Laser pointer
  93225. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  93226. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  93227. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93228. laserPointerMaterial.alpha = 0.6;
  93229. _this._laserPointer.material = laserPointerMaterial;
  93230. _this._laserPointer.rotation.x = Math.PI / 2;
  93231. _this._laserPointer.position.z = -0.5;
  93232. _this._laserPointer.isVisible = false;
  93233. _this._laserPointer.isPickable = false;
  93234. if (!webVRController.mesh) {
  93235. // Create an empty mesh that is used prior to loading the high quality model
  93236. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  93237. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  93238. preloadPointerPose.rotation.x = -0.7;
  93239. preloadMesh.addChild(preloadPointerPose);
  93240. webVRController.attachToMesh(preloadMesh);
  93241. }
  93242. _this._setLaserPointerParent(webVRController.mesh);
  93243. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  93244. _this._setLaserPointerParent(mesh);
  93245. });
  93246. return _this;
  93247. }
  93248. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  93249. return this.webVRController.getForwardRay(length);
  93250. };
  93251. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  93252. _super.prototype._activatePointer.call(this);
  93253. this._laserPointer.isVisible = true;
  93254. };
  93255. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  93256. _super.prototype._deactivatePointer.call(this);
  93257. this._laserPointer.isVisible = false;
  93258. };
  93259. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  93260. this._laserPointer.material.emissiveColor = color;
  93261. };
  93262. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  93263. var makeNotPick = function (root) {
  93264. root.isPickable = false;
  93265. root.getChildMeshes().forEach(function (c) {
  93266. makeNotPick(c);
  93267. });
  93268. };
  93269. makeNotPick(mesh);
  93270. var childMeshes = mesh.getChildMeshes();
  93271. this.webVRController._pointingPoseNode = null;
  93272. for (var i = 0; i < childMeshes.length; i++) {
  93273. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  93274. mesh = childMeshes[i];
  93275. this.webVRController._pointingPoseNode = mesh;
  93276. break;
  93277. }
  93278. }
  93279. this._laserPointer.parent = mesh;
  93280. };
  93281. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  93282. if (distance === void 0) { distance = 100; }
  93283. this._laserPointer.scaling.y = distance;
  93284. this._laserPointer.position.z = -distance / 2;
  93285. };
  93286. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  93287. _super.prototype.dispose.call(this);
  93288. this._laserPointer.dispose();
  93289. if (this._meshAttachedObserver) {
  93290. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  93291. }
  93292. };
  93293. return VRExperienceHelperControllerGazer;
  93294. }(VRExperienceHelperGazer));
  93295. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  93296. __extends(VRExperienceHelperCameraGazer, _super);
  93297. function VRExperienceHelperCameraGazer(getCamera, scene) {
  93298. var _this = _super.call(this, scene) || this;
  93299. _this.getCamera = getCamera;
  93300. return _this;
  93301. }
  93302. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  93303. var camera = this.getCamera();
  93304. if (camera) {
  93305. return camera.getForwardRay(length);
  93306. }
  93307. else {
  93308. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  93309. }
  93310. };
  93311. return VRExperienceHelperCameraGazer;
  93312. }(VRExperienceHelperGazer));
  93313. /**
  93314. * Helps to quickly add VR support to an existing scene.
  93315. * See http://doc.babylonjs.com/how_to/webvr_helper
  93316. */
  93317. var VRExperienceHelper = /** @class */ (function () {
  93318. /**
  93319. * Instantiates a VRExperienceHelper.
  93320. * Helps to quickly add VR support to an existing scene.
  93321. * @param scene The scene the VRExperienceHelper belongs to.
  93322. * @param webVROptions Options to modify the vr experience helper's behavior.
  93323. */
  93324. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  93325. if (webVROptions === void 0) { webVROptions = {}; }
  93326. var _this = this;
  93327. this.webVROptions = webVROptions;
  93328. // Can the system support WebVR, even if a headset isn't plugged in?
  93329. this._webVRsupported = false;
  93330. // If WebVR is supported, is a headset plugged in and are we ready to present?
  93331. this._webVRready = false;
  93332. // Are we waiting for the requestPresent callback to complete?
  93333. this._webVRrequesting = false;
  93334. // Are we presenting to the headset right now?
  93335. this._webVRpresenting = false;
  93336. // Are we presenting in the fullscreen fallback?
  93337. this._fullscreenVRpresenting = false;
  93338. /**
  93339. * Observable raised when entering VR.
  93340. */
  93341. this.onEnteringVRObservable = new BABYLON.Observable();
  93342. /**
  93343. * Observable raised when exiting VR.
  93344. */
  93345. this.onExitingVRObservable = new BABYLON.Observable();
  93346. /**
  93347. * Observable raised when controller mesh is loaded.
  93348. */
  93349. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93350. this._useCustomVRButton = false;
  93351. this._teleportationRequested = false;
  93352. this._teleportActive = false;
  93353. this._floorMeshesCollection = [];
  93354. this._rotationAllowed = true;
  93355. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  93356. this._isDefaultTeleportationTarget = true;
  93357. this._teleportationFillColor = "#444444";
  93358. this._teleportationBorderColor = "#FFFFFF";
  93359. this._rotationAngle = 0;
  93360. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  93361. this._padSensibilityUp = 0.65;
  93362. this._padSensibilityDown = 0.35;
  93363. this.leftController = null;
  93364. this.rightController = null;
  93365. /**
  93366. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  93367. */
  93368. this.onNewMeshSelected = new BABYLON.Observable();
  93369. /**
  93370. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  93371. */
  93372. this.onNewMeshPicked = new BABYLON.Observable();
  93373. /**
  93374. * Observable raised before camera teleportation
  93375. */
  93376. this.onBeforeCameraTeleport = new BABYLON.Observable();
  93377. /**
  93378. * Observable raised after camera teleportation
  93379. */
  93380. this.onAfterCameraTeleport = new BABYLON.Observable();
  93381. /**
  93382. * Observable raised when current selected mesh gets unselected
  93383. */
  93384. this.onSelectedMeshUnselected = new BABYLON.Observable();
  93385. /**
  93386. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  93387. */
  93388. this.teleportationEnabled = true;
  93389. this._teleportationInitialized = false;
  93390. this._interactionsEnabled = false;
  93391. this._interactionsRequested = false;
  93392. this._displayGaze = true;
  93393. this._displayLaserPointer = true;
  93394. this._onResize = function () {
  93395. _this.moveButtonToBottomRight();
  93396. if (_this._fullscreenVRpresenting && _this._webVRready) {
  93397. _this.exitVR();
  93398. }
  93399. };
  93400. this._onFullscreenChange = function () {
  93401. if (document.fullscreen !== undefined) {
  93402. _this._fullscreenVRpresenting = document.fullscreen;
  93403. }
  93404. else if (document.mozFullScreen !== undefined) {
  93405. _this._fullscreenVRpresenting = document.mozFullScreen;
  93406. }
  93407. else if (document.webkitIsFullScreen !== undefined) {
  93408. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  93409. }
  93410. else if (document.msIsFullScreen !== undefined) {
  93411. _this._fullscreenVRpresenting = document.msIsFullScreen;
  93412. }
  93413. else if (document.msFullscreenElement !== undefined) {
  93414. _this._fullscreenVRpresenting = document.msFullscreenElement;
  93415. }
  93416. if (!_this._fullscreenVRpresenting && _this._canvas) {
  93417. _this.exitVR();
  93418. if (!_this._useCustomVRButton) {
  93419. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  93420. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  93421. }
  93422. }
  93423. };
  93424. this.beforeRender = function () {
  93425. if (_this.leftController && _this.leftController._activePointer) {
  93426. _this._castRayAndSelectObject(_this.leftController);
  93427. }
  93428. if (_this.rightController && _this.rightController._activePointer) {
  93429. _this._castRayAndSelectObject(_this.rightController);
  93430. }
  93431. if (_this._noControllerIsActive) {
  93432. _this._castRayAndSelectObject(_this._cameraGazer);
  93433. }
  93434. else {
  93435. _this._cameraGazer._gazeTracker.isVisible = false;
  93436. }
  93437. };
  93438. this._onNewGamepadConnected = function (gamepad) {
  93439. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  93440. if (gamepad.leftStick) {
  93441. gamepad.onleftstickchanged(function (stickValues) {
  93442. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  93443. // Listening to classic/xbox gamepad only if no VR controller is active
  93444. if ((!_this.leftController && !_this.rightController) ||
  93445. ((_this.leftController && !_this.leftController._activePointer) &&
  93446. (_this.rightController && !_this.rightController._activePointer))) {
  93447. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  93448. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  93449. }
  93450. }
  93451. });
  93452. }
  93453. if (gamepad.rightStick) {
  93454. gamepad.onrightstickchanged(function (stickValues) {
  93455. if (_this._teleportationInitialized) {
  93456. _this._checkRotate(stickValues, _this._cameraGazer);
  93457. }
  93458. });
  93459. }
  93460. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  93461. gamepad.onbuttondown(function (buttonPressed) {
  93462. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93463. _this._cameraGazer._selectionPointerDown();
  93464. }
  93465. });
  93466. gamepad.onbuttonup(function (buttonPressed) {
  93467. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93468. _this._cameraGazer._selectionPointerUp();
  93469. }
  93470. });
  93471. }
  93472. }
  93473. else {
  93474. var webVRController = gamepad;
  93475. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  93476. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  93477. _this.rightController = controller;
  93478. }
  93479. else {
  93480. _this.leftController = controller;
  93481. }
  93482. _this._tryEnableInteractionOnController(controller);
  93483. }
  93484. };
  93485. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  93486. this._tryEnableInteractionOnController = function (controller) {
  93487. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  93488. _this._enableInteractionOnController(controller);
  93489. }
  93490. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  93491. _this._enableTeleportationOnController(controller);
  93492. }
  93493. };
  93494. this._onNewGamepadDisconnected = function (gamepad) {
  93495. if (gamepad instanceof BABYLON.WebVRController) {
  93496. if (gamepad.hand === "left" && _this.leftController != null) {
  93497. _this.leftController.dispose();
  93498. _this.leftController = null;
  93499. }
  93500. if (gamepad.hand === "right" && _this.rightController != null) {
  93501. _this.rightController.dispose();
  93502. _this.rightController = null;
  93503. }
  93504. }
  93505. };
  93506. this._workingVector = BABYLON.Vector3.Zero();
  93507. this._workingQuaternion = BABYLON.Quaternion.Identity();
  93508. this._workingMatrix = BABYLON.Matrix.Identity();
  93509. this._scene = scene;
  93510. this._canvas = scene.getEngine().getRenderingCanvas();
  93511. // Parse options
  93512. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  93513. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  93514. }
  93515. if (webVROptions.createDeviceOrientationCamera === undefined) {
  93516. webVROptions.createDeviceOrientationCamera = true;
  93517. }
  93518. if (webVROptions.laserToggle === undefined) {
  93519. webVROptions.laserToggle = true;
  93520. }
  93521. if (webVROptions.defaultHeight === undefined) {
  93522. webVROptions.defaultHeight = 1.7;
  93523. }
  93524. if (webVROptions.useCustomVRButton) {
  93525. this._useCustomVRButton = true;
  93526. if (webVROptions.customVRButton) {
  93527. this._btnVR = webVROptions.customVRButton;
  93528. }
  93529. }
  93530. if (webVROptions.rayLength) {
  93531. this._rayLength = webVROptions.rayLength;
  93532. }
  93533. this._defaultHeight = webVROptions.defaultHeight;
  93534. if (webVROptions.positionScale) {
  93535. this._rayLength *= webVROptions.positionScale;
  93536. this._defaultHeight *= webVROptions.positionScale;
  93537. }
  93538. // Set position
  93539. if (this._scene.activeCamera) {
  93540. this._position = this._scene.activeCamera.position.clone();
  93541. }
  93542. else {
  93543. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  93544. }
  93545. // Set non-vr camera
  93546. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  93547. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  93548. // Copy data from existing camera
  93549. if (this._scene.activeCamera) {
  93550. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93551. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  93552. // Set rotation from previous camera
  93553. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  93554. var targetCamera = this._scene.activeCamera;
  93555. if (targetCamera.rotationQuaternion) {
  93556. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  93557. }
  93558. else {
  93559. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  93560. }
  93561. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  93562. }
  93563. }
  93564. this._scene.activeCamera = this._deviceOrientationCamera;
  93565. if (this._canvas) {
  93566. this._scene.activeCamera.attachControl(this._canvas);
  93567. }
  93568. }
  93569. else {
  93570. this._existingCamera = this._scene.activeCamera;
  93571. }
  93572. // Create VR cameras
  93573. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93574. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  93575. }
  93576. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  93577. this._webVRCamera.useStandingMatrix();
  93578. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  93579. // Create default button
  93580. if (!this._useCustomVRButton) {
  93581. this._btnVR = document.createElement("BUTTON");
  93582. this._btnVR.className = "babylonVRicon";
  93583. this._btnVR.id = "babylonVRiconbtn";
  93584. this._btnVR.title = "Click to switch to VR";
  93585. var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
  93586. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  93587. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  93588. // css += ".babylonVRicon.vrdisplaysupported { }";
  93589. // css += ".babylonVRicon.vrdisplayready { }";
  93590. // css += ".babylonVRicon.vrdisplayrequesting { }";
  93591. var style = document.createElement('style');
  93592. style.appendChild(document.createTextNode(css));
  93593. document.getElementsByTagName('head')[0].appendChild(style);
  93594. this.moveButtonToBottomRight();
  93595. }
  93596. // VR button click event
  93597. if (this._btnVR) {
  93598. this._btnVR.addEventListener("click", function () {
  93599. if (!_this.isInVRMode) {
  93600. _this.enterVR();
  93601. }
  93602. else {
  93603. _this.exitVR();
  93604. }
  93605. });
  93606. }
  93607. // Window events
  93608. window.addEventListener("resize", this._onResize);
  93609. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  93610. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  93611. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  93612. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  93613. document.onmsfullscreenchange = this._onFullscreenChange;
  93614. // Display vr button when headset is connected
  93615. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93616. this.displayVRButton();
  93617. }
  93618. else {
  93619. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  93620. if (e.vrDisplay) {
  93621. _this.displayVRButton();
  93622. }
  93623. });
  93624. }
  93625. // Exiting VR mode using 'ESC' key on desktop
  93626. this._onKeyDown = function (event) {
  93627. if (event.keyCode === 27 && _this.isInVRMode) {
  93628. _this.exitVR();
  93629. }
  93630. };
  93631. document.addEventListener("keydown", this._onKeyDown);
  93632. // Exiting VR mode double tapping the touch screen
  93633. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  93634. if (_this.isInVRMode) {
  93635. _this.exitVR();
  93636. if (_this._fullscreenVRpresenting) {
  93637. _this._scene.getEngine().switchFullscreen(true);
  93638. }
  93639. }
  93640. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  93641. // Listen for WebVR display changes
  93642. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  93643. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  93644. this._onVRRequestPresentStart = function () {
  93645. _this._webVRrequesting = true;
  93646. _this.updateButtonVisibility();
  93647. };
  93648. this._onVRRequestPresentComplete = function (success) {
  93649. _this._webVRrequesting = false;
  93650. _this.updateButtonVisibility();
  93651. };
  93652. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  93653. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  93654. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  93655. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93656. scene.onDisposeObservable.add(function () {
  93657. _this.dispose();
  93658. });
  93659. // Gamepad connection events
  93660. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  93661. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  93662. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  93663. this.updateButtonVisibility();
  93664. //create easing functions
  93665. this._circleEase = new BABYLON.CircleEase();
  93666. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93667. if (this.webVROptions.floorMeshes) {
  93668. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  93669. }
  93670. }
  93671. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  93672. /** Return this.onEnteringVRObservable
  93673. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  93674. */
  93675. get: function () {
  93676. return this.onEnteringVRObservable;
  93677. },
  93678. enumerable: true,
  93679. configurable: true
  93680. });
  93681. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  93682. /** Return this.onExitingVRObservable
  93683. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  93684. */
  93685. get: function () {
  93686. return this.onExitingVRObservable;
  93687. },
  93688. enumerable: true,
  93689. configurable: true
  93690. });
  93691. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  93692. /** Return this.onControllerMeshLoadedObservable
  93693. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  93694. */
  93695. get: function () {
  93696. return this.onControllerMeshLoadedObservable;
  93697. },
  93698. enumerable: true,
  93699. configurable: true
  93700. });
  93701. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  93702. /**
  93703. * The mesh used to display where the user is going to teleport.
  93704. */
  93705. get: function () {
  93706. return this._teleportationTarget;
  93707. },
  93708. /**
  93709. * Sets the mesh to be used to display where the user is going to teleport.
  93710. */
  93711. set: function (value) {
  93712. if (value) {
  93713. value.name = "teleportationTarget";
  93714. this._isDefaultTeleportationTarget = false;
  93715. this._teleportationTarget = value;
  93716. }
  93717. },
  93718. enumerable: true,
  93719. configurable: true
  93720. });
  93721. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  93722. /**
  93723. * The mesh used to display where the user is selecting,
  93724. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  93725. * See http://doc.babylonjs.com/resources/baking_transformations
  93726. */
  93727. get: function () {
  93728. return this._cameraGazer._gazeTracker;
  93729. },
  93730. set: function (value) {
  93731. if (value) {
  93732. this._cameraGazer._gazeTracker = value;
  93733. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  93734. this._cameraGazer._gazeTracker.isPickable = false;
  93735. this._cameraGazer._gazeTracker.isVisible = false;
  93736. this._cameraGazer._gazeTracker.name = "gazeTracker";
  93737. if (this.leftController) {
  93738. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93739. }
  93740. if (this.rightController) {
  93741. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93742. }
  93743. }
  93744. },
  93745. enumerable: true,
  93746. configurable: true
  93747. });
  93748. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  93749. /**
  93750. * If the ray of the gaze should be displayed.
  93751. */
  93752. get: function () {
  93753. return this._displayGaze;
  93754. },
  93755. /**
  93756. * Sets if the ray of the gaze should be displayed.
  93757. */
  93758. set: function (value) {
  93759. this._displayGaze = value;
  93760. if (!value) {
  93761. this._cameraGazer._gazeTracker.isVisible = false;
  93762. if (this.leftController) {
  93763. this.leftController._gazeTracker.isVisible = false;
  93764. }
  93765. if (this.rightController) {
  93766. this.rightController._gazeTracker.isVisible = false;
  93767. }
  93768. }
  93769. },
  93770. enumerable: true,
  93771. configurable: true
  93772. });
  93773. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  93774. /**
  93775. * If the ray of the LaserPointer should be displayed.
  93776. */
  93777. get: function () {
  93778. return this._displayLaserPointer;
  93779. },
  93780. /**
  93781. * Sets if the ray of the LaserPointer should be displayed.
  93782. */
  93783. set: function (value) {
  93784. this._displayLaserPointer = value;
  93785. if (!value) {
  93786. if (this.rightController) {
  93787. this.rightController._deactivatePointer();
  93788. this.rightController._gazeTracker.isVisible = false;
  93789. }
  93790. if (this.leftController) {
  93791. this.leftController._deactivatePointer();
  93792. this.leftController._gazeTracker.isVisible = false;
  93793. }
  93794. }
  93795. else {
  93796. if (this.rightController) {
  93797. this.rightController._activatePointer();
  93798. }
  93799. if (this.leftController) {
  93800. this.leftController._activatePointer();
  93801. }
  93802. }
  93803. },
  93804. enumerable: true,
  93805. configurable: true
  93806. });
  93807. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93808. /**
  93809. * The deviceOrientationCamera used as the camera when not in VR.
  93810. */
  93811. get: function () {
  93812. return this._deviceOrientationCamera;
  93813. },
  93814. enumerable: true,
  93815. configurable: true
  93816. });
  93817. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93818. /**
  93819. * Based on the current WebVR support, returns the current VR camera used.
  93820. */
  93821. get: function () {
  93822. if (this._webVRready) {
  93823. return this._webVRCamera;
  93824. }
  93825. else {
  93826. return this._scene.activeCamera;
  93827. }
  93828. },
  93829. enumerable: true,
  93830. configurable: true
  93831. });
  93832. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93833. /**
  93834. * The webVRCamera which is used when in VR.
  93835. */
  93836. get: function () {
  93837. return this._webVRCamera;
  93838. },
  93839. enumerable: true,
  93840. configurable: true
  93841. });
  93842. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93843. /**
  93844. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93845. */
  93846. get: function () {
  93847. return this._vrDeviceOrientationCamera;
  93848. },
  93849. enumerable: true,
  93850. configurable: true
  93851. });
  93852. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93853. get: function () {
  93854. var result = this._cameraGazer._teleportationRequestInitiated
  93855. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93856. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93857. return result;
  93858. },
  93859. enumerable: true,
  93860. configurable: true
  93861. });
  93862. // Raised when one of the controller has loaded successfully its associated default mesh
  93863. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93864. if (this.leftController && this.leftController.webVRController == webVRController) {
  93865. if (webVRController.mesh) {
  93866. this.leftController._setLaserPointerParent(webVRController.mesh);
  93867. }
  93868. }
  93869. if (this.rightController && this.rightController.webVRController == webVRController) {
  93870. if (webVRController.mesh) {
  93871. this.rightController._setLaserPointerParent(webVRController.mesh);
  93872. }
  93873. }
  93874. try {
  93875. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93876. }
  93877. catch (err) {
  93878. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93879. }
  93880. };
  93881. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93882. /**
  93883. * Gets a value indicating if we are currently in VR mode.
  93884. */
  93885. get: function () {
  93886. return this._webVRpresenting || this._fullscreenVRpresenting;
  93887. },
  93888. enumerable: true,
  93889. configurable: true
  93890. });
  93891. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93892. var vrDisplay = this._scene.getEngine().getVRDevice();
  93893. if (vrDisplay) {
  93894. var wasPresenting = this._webVRpresenting;
  93895. // A VR display is connected
  93896. this._webVRpresenting = vrDisplay.isPresenting;
  93897. if (wasPresenting && !this._webVRpresenting)
  93898. this.exitVR();
  93899. }
  93900. else {
  93901. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93902. }
  93903. this.updateButtonVisibility();
  93904. };
  93905. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93906. this._webVRsupported = eventArgs.vrSupported;
  93907. this._webVRready = !!eventArgs.vrDisplay;
  93908. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93909. this.updateButtonVisibility();
  93910. };
  93911. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93912. if (this._canvas && !this._useCustomVRButton) {
  93913. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93914. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93915. }
  93916. };
  93917. VRExperienceHelper.prototype.displayVRButton = function () {
  93918. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93919. document.body.appendChild(this._btnVR);
  93920. this._btnVRDisplayed = true;
  93921. }
  93922. };
  93923. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93924. if (!this._btnVR || this._useCustomVRButton) {
  93925. return;
  93926. }
  93927. this._btnVR.className = "babylonVRicon";
  93928. if (this.isInVRMode) {
  93929. this._btnVR.className += " vrdisplaypresenting";
  93930. }
  93931. else {
  93932. if (this._webVRready)
  93933. this._btnVR.className += " vrdisplayready";
  93934. if (this._webVRsupported)
  93935. this._btnVR.className += " vrdisplaysupported";
  93936. if (this._webVRrequesting)
  93937. this._btnVR.className += " vrdisplayrequesting";
  93938. }
  93939. };
  93940. /**
  93941. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93942. * Otherwise, will use the fullscreen API.
  93943. */
  93944. VRExperienceHelper.prototype.enterVR = function () {
  93945. if (this.onEnteringVRObservable) {
  93946. try {
  93947. this.onEnteringVRObservable.notifyObservers(this);
  93948. }
  93949. catch (err) {
  93950. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93951. }
  93952. }
  93953. if (this._scene.activeCamera) {
  93954. this._position = this._scene.activeCamera.position.clone();
  93955. // make sure that we return to the last active camera
  93956. this._existingCamera = this._scene.activeCamera;
  93957. }
  93958. if (this._webVRrequesting)
  93959. return;
  93960. // If WebVR is supported and a headset is connected
  93961. if (this._webVRready) {
  93962. if (!this._webVRpresenting) {
  93963. this._webVRCamera.position = this._position;
  93964. this._scene.activeCamera = this._webVRCamera;
  93965. }
  93966. }
  93967. else if (this._vrDeviceOrientationCamera) {
  93968. this._vrDeviceOrientationCamera.position = this._position;
  93969. if (this._scene.activeCamera) {
  93970. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93971. }
  93972. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93973. this._scene.getEngine().switchFullscreen(true);
  93974. this.updateButtonVisibility();
  93975. }
  93976. if (this._scene.activeCamera && this._canvas) {
  93977. this._scene.activeCamera.attachControl(this._canvas);
  93978. }
  93979. if (this._interactionsEnabled) {
  93980. this._scene.registerBeforeRender(this.beforeRender);
  93981. }
  93982. };
  93983. /**
  93984. * Attempt to exit VR, or fullscreen.
  93985. */
  93986. VRExperienceHelper.prototype.exitVR = function () {
  93987. if (this.onExitingVRObservable) {
  93988. try {
  93989. this.onExitingVRObservable.notifyObservers(this);
  93990. }
  93991. catch (err) {
  93992. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93993. }
  93994. }
  93995. if (this._webVRpresenting) {
  93996. this._scene.getEngine().disableVR();
  93997. }
  93998. if (this._scene.activeCamera) {
  93999. this._position = this._scene.activeCamera.position.clone();
  94000. }
  94001. if (this._deviceOrientationCamera) {
  94002. this._deviceOrientationCamera.position = this._position;
  94003. this._scene.activeCamera = this._deviceOrientationCamera;
  94004. if (this._canvas) {
  94005. this._scene.activeCamera.attachControl(this._canvas);
  94006. }
  94007. }
  94008. else if (this._existingCamera) {
  94009. this._existingCamera.position = this._position;
  94010. this._scene.activeCamera = this._existingCamera;
  94011. }
  94012. this.updateButtonVisibility();
  94013. if (this._interactionsEnabled) {
  94014. this._scene.unregisterBeforeRender(this.beforeRender);
  94015. }
  94016. // resize to update width and height when exiting vr exits fullscreen
  94017. this._scene.getEngine().resize();
  94018. };
  94019. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  94020. /**
  94021. * The position of the vr experience helper.
  94022. */
  94023. get: function () {
  94024. return this._position;
  94025. },
  94026. /**
  94027. * Sets the position of the vr experience helper.
  94028. */
  94029. set: function (value) {
  94030. this._position = value;
  94031. if (this._scene.activeCamera) {
  94032. this._scene.activeCamera.position = value;
  94033. }
  94034. },
  94035. enumerable: true,
  94036. configurable: true
  94037. });
  94038. /**
  94039. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  94040. */
  94041. VRExperienceHelper.prototype.enableInteractions = function () {
  94042. var _this = this;
  94043. if (!this._interactionsEnabled) {
  94044. this._interactionsRequested = true;
  94045. if (this.leftController) {
  94046. this._enableInteractionOnController(this.leftController);
  94047. }
  94048. if (this.rightController) {
  94049. this._enableInteractionOnController(this.rightController);
  94050. }
  94051. this.raySelectionPredicate = function (mesh) {
  94052. return mesh.isVisible && mesh.isPickable;
  94053. };
  94054. this.meshSelectionPredicate = function (mesh) {
  94055. return true;
  94056. };
  94057. this._raySelectionPredicate = function (mesh) {
  94058. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  94059. && mesh.name.indexOf("teleportationTarget") === -1
  94060. && mesh.name.indexOf("torusTeleportation") === -1)) {
  94061. return _this.raySelectionPredicate(mesh);
  94062. }
  94063. return false;
  94064. };
  94065. this._interactionsEnabled = true;
  94066. }
  94067. };
  94068. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  94069. get: function () {
  94070. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  94071. },
  94072. enumerable: true,
  94073. configurable: true
  94074. });
  94075. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  94076. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  94077. if (this._floorMeshesCollection[i].id === mesh.id) {
  94078. return true;
  94079. }
  94080. }
  94081. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  94082. return true;
  94083. }
  94084. return false;
  94085. };
  94086. /**
  94087. * Adds a floor mesh to be used for teleportation.
  94088. * @param floorMesh the mesh to be used for teleportation.
  94089. */
  94090. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  94091. if (!this._floorMeshesCollection) {
  94092. return;
  94093. }
  94094. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  94095. return;
  94096. }
  94097. this._floorMeshesCollection.push(floorMesh);
  94098. };
  94099. /**
  94100. * Removes a floor mesh from being used for teleportation.
  94101. * @param floorMesh the mesh to be removed.
  94102. */
  94103. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  94104. if (!this._floorMeshesCollection) {
  94105. return;
  94106. }
  94107. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  94108. if (meshIndex !== -1) {
  94109. this._floorMeshesCollection.splice(meshIndex, 1);
  94110. }
  94111. };
  94112. /**
  94113. * Enables interactions and teleportation using the VR controllers and gaze.
  94114. * @param vrTeleportationOptions options to modify teleportation behavior.
  94115. */
  94116. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  94117. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  94118. if (!this._teleportationInitialized) {
  94119. this._teleportationRequested = true;
  94120. this.enableInteractions();
  94121. if (vrTeleportationOptions.floorMeshName) {
  94122. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  94123. }
  94124. if (vrTeleportationOptions.floorMeshes) {
  94125. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  94126. }
  94127. if (this.leftController != null) {
  94128. this._enableTeleportationOnController(this.leftController);
  94129. }
  94130. if (this.rightController != null) {
  94131. this._enableTeleportationOnController(this.rightController);
  94132. }
  94133. // Creates an image processing post process for the vignette not relying
  94134. // on the main scene configuration for image processing to reduce setup and spaces
  94135. // (gamma/linear) conflicts.
  94136. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  94137. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  94138. imageProcessingConfiguration.vignetteEnabled = true;
  94139. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  94140. this._webVRCamera.detachPostProcess(this._postProcessMove);
  94141. this._teleportationInitialized = true;
  94142. if (this._isDefaultTeleportationTarget) {
  94143. this._createTeleportationCircles();
  94144. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  94145. }
  94146. }
  94147. };
  94148. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  94149. var _this = this;
  94150. var controllerMesh = controller.webVRController.mesh;
  94151. if (controllerMesh) {
  94152. controller._interactionsEnabled = true;
  94153. controller._activatePointer();
  94154. if (this.webVROptions.laserToggle) {
  94155. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  94156. // Enabling / disabling laserPointer
  94157. if (_this._displayLaserPointer && stateObject.value === 1) {
  94158. if (controller._activePointer) {
  94159. controller._deactivatePointer();
  94160. }
  94161. else {
  94162. controller._activatePointer();
  94163. }
  94164. if (_this.displayGaze) {
  94165. controller._gazeTracker.isVisible = controller._activePointer;
  94166. }
  94167. }
  94168. });
  94169. }
  94170. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  94171. var gazer = controller;
  94172. if (_this._noControllerIsActive) {
  94173. gazer = _this._cameraGazer;
  94174. }
  94175. if (!gazer._pointerDownOnMeshAsked) {
  94176. if (stateObject.value > _this._padSensibilityUp) {
  94177. gazer._selectionPointerDown();
  94178. }
  94179. }
  94180. else if (stateObject.value < _this._padSensibilityDown) {
  94181. gazer._selectionPointerUp();
  94182. }
  94183. });
  94184. }
  94185. };
  94186. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  94187. // Dont teleport if another gaze already requested teleportation
  94188. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  94189. return;
  94190. }
  94191. if (!gazer._teleportationRequestInitiated) {
  94192. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  94193. gazer._activatePointer();
  94194. gazer._teleportationRequestInitiated = true;
  94195. }
  94196. }
  94197. else {
  94198. // Listening to the proper controller values changes to confirm teleportation
  94199. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  94200. if (this._teleportActive) {
  94201. this._teleportCamera(this._haloCenter);
  94202. }
  94203. gazer._teleportationRequestInitiated = false;
  94204. }
  94205. }
  94206. };
  94207. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  94208. // Only rotate when user is not currently selecting a teleportation location
  94209. if (gazer._teleportationRequestInitiated) {
  94210. return;
  94211. }
  94212. if (!gazer._rotationLeftAsked) {
  94213. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  94214. gazer._rotationLeftAsked = true;
  94215. if (this._rotationAllowed) {
  94216. this._rotateCamera(false);
  94217. }
  94218. }
  94219. }
  94220. else {
  94221. if (stateObject.x > -this._padSensibilityDown) {
  94222. gazer._rotationLeftAsked = false;
  94223. }
  94224. }
  94225. if (!gazer._rotationRightAsked) {
  94226. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  94227. gazer._rotationRightAsked = true;
  94228. if (this._rotationAllowed) {
  94229. this._rotateCamera(true);
  94230. }
  94231. }
  94232. }
  94233. else {
  94234. if (stateObject.x < this._padSensibilityDown) {
  94235. gazer._rotationRightAsked = false;
  94236. }
  94237. }
  94238. };
  94239. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  94240. // Only teleport backwards when user is not currently selecting a teleportation location
  94241. if (gazer._teleportationRequestInitiated) {
  94242. return;
  94243. }
  94244. // Teleport backwards
  94245. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  94246. if (!gazer._teleportationBackRequestInitiated) {
  94247. if (!this.currentVRCamera) {
  94248. return;
  94249. }
  94250. // Get rotation and position of the current camera
  94251. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  94252. var position = this.currentVRCamera.position;
  94253. // If the camera has device position, use that instead
  94254. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  94255. rotation = this.currentVRCamera.deviceRotationQuaternion;
  94256. position = this.currentVRCamera.devicePosition;
  94257. }
  94258. // Get matrix with only the y rotation of the device rotation
  94259. rotation.toEulerAnglesToRef(this._workingVector);
  94260. this._workingVector.z = 0;
  94261. this._workingVector.x = 0;
  94262. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  94263. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  94264. // Rotate backwards ray by device rotation to cast at the ground behind the user
  94265. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  94266. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  94267. var ray = new BABYLON.Ray(position, this._workingVector);
  94268. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94269. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  94270. this._teleportCamera(hit.pickedPoint);
  94271. }
  94272. gazer._teleportationBackRequestInitiated = true;
  94273. }
  94274. }
  94275. else {
  94276. gazer._teleportationBackRequestInitiated = false;
  94277. }
  94278. };
  94279. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  94280. var _this = this;
  94281. var controllerMesh = controller.webVRController.mesh;
  94282. if (controllerMesh) {
  94283. if (!controller._interactionsEnabled) {
  94284. this._enableInteractionOnController(controller);
  94285. }
  94286. controller._interactionsEnabled = true;
  94287. controller._teleportationEnabled = true;
  94288. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94289. controller._dpadPressed = false;
  94290. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  94291. controller._dpadPressed = stateObject.pressed;
  94292. if (!controller._dpadPressed) {
  94293. controller._rotationLeftAsked = false;
  94294. controller._rotationRightAsked = false;
  94295. controller._teleportationBackRequestInitiated = false;
  94296. }
  94297. });
  94298. }
  94299. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  94300. if (_this.teleportationEnabled) {
  94301. _this._checkTeleportBackwards(stateObject, controller);
  94302. _this._checkTeleportWithRay(stateObject, controller);
  94303. }
  94304. _this._checkRotate(stateObject, controller);
  94305. });
  94306. }
  94307. };
  94308. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  94309. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  94310. this._teleportationTarget.isPickable = false;
  94311. var length = 512;
  94312. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  94313. dynamicTexture.hasAlpha = true;
  94314. var context = dynamicTexture.getContext();
  94315. var centerX = length / 2;
  94316. var centerY = length / 2;
  94317. var radius = 200;
  94318. context.beginPath();
  94319. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  94320. context.fillStyle = this._teleportationFillColor;
  94321. context.fill();
  94322. context.lineWidth = 10;
  94323. context.strokeStyle = this._teleportationBorderColor;
  94324. context.stroke();
  94325. context.closePath();
  94326. dynamicTexture.update();
  94327. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  94328. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  94329. this._teleportationTarget.material = teleportationCircleMaterial;
  94330. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  94331. torus.isPickable = false;
  94332. torus.parent = this._teleportationTarget;
  94333. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  94334. var keys = [];
  94335. keys.push({
  94336. frame: 0,
  94337. value: 0
  94338. });
  94339. keys.push({
  94340. frame: 30,
  94341. value: 0.4
  94342. });
  94343. keys.push({
  94344. frame: 60,
  94345. value: 0
  94346. });
  94347. animationInnerCircle.setKeys(keys);
  94348. var easingFunction = new BABYLON.SineEase();
  94349. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94350. animationInnerCircle.setEasingFunction(easingFunction);
  94351. torus.animations = [];
  94352. torus.animations.push(animationInnerCircle);
  94353. this._scene.beginAnimation(torus, 0, 60, true);
  94354. this._hideTeleportationTarget();
  94355. };
  94356. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  94357. this._teleportActive = true;
  94358. if (this._teleportationInitialized) {
  94359. this._teleportationTarget.isVisible = true;
  94360. if (this._isDefaultTeleportationTarget) {
  94361. this._teleportationTarget.getChildren()[0].isVisible = true;
  94362. }
  94363. }
  94364. };
  94365. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  94366. this._teleportActive = false;
  94367. if (this._teleportationInitialized) {
  94368. this._teleportationTarget.isVisible = false;
  94369. if (this._isDefaultTeleportationTarget) {
  94370. this._teleportationTarget.getChildren()[0].isVisible = false;
  94371. }
  94372. }
  94373. };
  94374. VRExperienceHelper.prototype._rotateCamera = function (right) {
  94375. var _this = this;
  94376. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94377. return;
  94378. }
  94379. if (right) {
  94380. this._rotationAngle++;
  94381. }
  94382. else {
  94383. this._rotationAngle--;
  94384. }
  94385. this.currentVRCamera.animations = [];
  94386. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  94387. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94388. var animationRotationKeys = [];
  94389. animationRotationKeys.push({
  94390. frame: 0,
  94391. value: this.currentVRCamera.rotationQuaternion
  94392. });
  94393. animationRotationKeys.push({
  94394. frame: 6,
  94395. value: target
  94396. });
  94397. animationRotation.setKeys(animationRotationKeys);
  94398. animationRotation.setEasingFunction(this._circleEase);
  94399. this.currentVRCamera.animations.push(animationRotation);
  94400. this._postProcessMove.animations = [];
  94401. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94402. var vignetteWeightKeys = [];
  94403. vignetteWeightKeys.push({
  94404. frame: 0,
  94405. value: 0
  94406. });
  94407. vignetteWeightKeys.push({
  94408. frame: 3,
  94409. value: 4
  94410. });
  94411. vignetteWeightKeys.push({
  94412. frame: 6,
  94413. value: 0
  94414. });
  94415. animationPP.setKeys(vignetteWeightKeys);
  94416. animationPP.setEasingFunction(this._circleEase);
  94417. this._postProcessMove.animations.push(animationPP);
  94418. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94419. var vignetteStretchKeys = [];
  94420. vignetteStretchKeys.push({
  94421. frame: 0,
  94422. value: 0
  94423. });
  94424. vignetteStretchKeys.push({
  94425. frame: 3,
  94426. value: 10
  94427. });
  94428. vignetteStretchKeys.push({
  94429. frame: 6,
  94430. value: 0
  94431. });
  94432. animationPP2.setKeys(vignetteStretchKeys);
  94433. animationPP2.setEasingFunction(this._circleEase);
  94434. this._postProcessMove.animations.push(animationPP2);
  94435. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94436. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94437. this._postProcessMove.samples = 4;
  94438. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94439. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  94440. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94441. });
  94442. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  94443. };
  94444. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  94445. if (hit.pickedPoint) {
  94446. if (gazer._teleportationRequestInitiated) {
  94447. this._displayTeleportationTarget();
  94448. this._haloCenter.copyFrom(hit.pickedPoint);
  94449. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  94450. }
  94451. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  94452. if (pickNormal) {
  94453. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94454. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94455. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  94456. }
  94457. this._teleportationTarget.position.y += 0.1;
  94458. }
  94459. };
  94460. VRExperienceHelper.prototype._teleportCamera = function (location) {
  94461. var _this = this;
  94462. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94463. return;
  94464. }
  94465. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  94466. // offset of the headset from the anchor.
  94467. if (this.webVRCamera.leftCamera) {
  94468. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  94469. this._workingVector.subtractInPlace(this.webVRCamera.position);
  94470. location.subtractToRef(this._workingVector, this._workingVector);
  94471. }
  94472. else {
  94473. this._workingVector.copyFrom(location);
  94474. }
  94475. // Add height to account for user's height offset
  94476. if (this.isInVRMode) {
  94477. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  94478. }
  94479. else {
  94480. this._workingVector.y += this._defaultHeight;
  94481. }
  94482. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  94483. // Create animation from the camera's position to the new location
  94484. this.currentVRCamera.animations = [];
  94485. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94486. var animationCameraTeleportationKeys = [{
  94487. frame: 0,
  94488. value: this.currentVRCamera.position
  94489. },
  94490. {
  94491. frame: 11,
  94492. value: this._workingVector
  94493. }
  94494. ];
  94495. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  94496. animationCameraTeleportation.setEasingFunction(this._circleEase);
  94497. this.currentVRCamera.animations.push(animationCameraTeleportation);
  94498. this._postProcessMove.animations = [];
  94499. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94500. var vignetteWeightKeys = [];
  94501. vignetteWeightKeys.push({
  94502. frame: 0,
  94503. value: 0
  94504. });
  94505. vignetteWeightKeys.push({
  94506. frame: 5,
  94507. value: 8
  94508. });
  94509. vignetteWeightKeys.push({
  94510. frame: 11,
  94511. value: 0
  94512. });
  94513. animationPP.setKeys(vignetteWeightKeys);
  94514. this._postProcessMove.animations.push(animationPP);
  94515. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94516. var vignetteStretchKeys = [];
  94517. vignetteStretchKeys.push({
  94518. frame: 0,
  94519. value: 0
  94520. });
  94521. vignetteStretchKeys.push({
  94522. frame: 5,
  94523. value: 10
  94524. });
  94525. vignetteStretchKeys.push({
  94526. frame: 11,
  94527. value: 0
  94528. });
  94529. animationPP2.setKeys(vignetteStretchKeys);
  94530. this._postProcessMove.animations.push(animationPP2);
  94531. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94532. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94533. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94534. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  94535. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94536. });
  94537. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  94538. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  94539. });
  94540. this._hideTeleportationTarget();
  94541. };
  94542. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  94543. if (normal) {
  94544. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  94545. if (angle < Math.PI / 2) {
  94546. normal.scaleInPlace(-1);
  94547. }
  94548. }
  94549. return normal;
  94550. };
  94551. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  94552. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94553. return;
  94554. }
  94555. var ray = gazer._getForwardRay(this._rayLength);
  94556. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94557. if (hit) {
  94558. // Populate the contrllers mesh that can be used for drag/drop
  94559. if (gazer._laserPointer) {
  94560. hit.originMesh = gazer._laserPointer.parent;
  94561. }
  94562. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  94563. }
  94564. gazer._currentHit = hit;
  94565. // Moving the gazeTracker on the mesh face targetted
  94566. if (hit && hit.pickedPoint) {
  94567. if (this._displayGaze) {
  94568. var multiplier = 1;
  94569. gazer._gazeTracker.isVisible = true;
  94570. if (gazer._isActionableMesh) {
  94571. multiplier = 3;
  94572. }
  94573. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  94574. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  94575. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  94576. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  94577. // To avoid z-fighting
  94578. var deltaFighting = 0.002;
  94579. if (pickNormal) {
  94580. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94581. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94582. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  94583. }
  94584. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  94585. if (gazer._gazeTracker.position.x < 0) {
  94586. gazer._gazeTracker.position.x += deltaFighting;
  94587. }
  94588. else {
  94589. gazer._gazeTracker.position.x -= deltaFighting;
  94590. }
  94591. if (gazer._gazeTracker.position.y < 0) {
  94592. gazer._gazeTracker.position.y += deltaFighting;
  94593. }
  94594. else {
  94595. gazer._gazeTracker.position.y -= deltaFighting;
  94596. }
  94597. if (gazer._gazeTracker.position.z < 0) {
  94598. gazer._gazeTracker.position.z += deltaFighting;
  94599. }
  94600. else {
  94601. gazer._gazeTracker.position.z -= deltaFighting;
  94602. }
  94603. }
  94604. // Changing the size of the laser pointer based on the distance from the targetted point
  94605. gazer._updatePointerDistance(hit.distance);
  94606. }
  94607. else {
  94608. gazer._updatePointerDistance();
  94609. gazer._gazeTracker.isVisible = false;
  94610. }
  94611. if (hit && hit.pickedMesh) {
  94612. // The object selected is the floor, we're in a teleportation scenario
  94613. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  94614. // Moving the teleportation area to this targetted point
  94615. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  94616. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  94617. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94618. }
  94619. gazer._currentMeshSelected = null;
  94620. if (gazer._teleportationRequestInitiated) {
  94621. this._moveTeleportationSelectorTo(hit, gazer, ray);
  94622. }
  94623. return;
  94624. }
  94625. // If not, we're in a selection scenario
  94626. //this._teleportationAllowed = false;
  94627. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  94628. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  94629. this.onNewMeshPicked.notifyObservers(hit);
  94630. gazer._currentMeshSelected = hit.pickedMesh;
  94631. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  94632. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  94633. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  94634. gazer._isActionableMesh = true;
  94635. }
  94636. else {
  94637. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94638. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94639. gazer._isActionableMesh = false;
  94640. }
  94641. try {
  94642. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  94643. }
  94644. catch (err) {
  94645. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  94646. }
  94647. }
  94648. else {
  94649. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94650. gazer._currentMeshSelected = null;
  94651. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94652. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94653. }
  94654. }
  94655. }
  94656. else {
  94657. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94658. gazer._currentMeshSelected = null;
  94659. //this._teleportationAllowed = false;
  94660. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94661. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94662. }
  94663. };
  94664. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  94665. if (mesh) {
  94666. this.onSelectedMeshUnselected.notifyObservers(mesh);
  94667. }
  94668. };
  94669. /**
  94670. * Sets the color of the laser ray from the vr controllers.
  94671. * @param color new color for the ray.
  94672. */
  94673. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  94674. if (this.leftController) {
  94675. this.leftController._setLaserPointerColor(color);
  94676. }
  94677. if (this.rightController) {
  94678. this.rightController._setLaserPointerColor(color);
  94679. }
  94680. };
  94681. /**
  94682. * Sets the color of the ray from the vr headsets gaze.
  94683. * @param color new color for the ray.
  94684. */
  94685. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  94686. if (!this._cameraGazer._gazeTracker.material) {
  94687. return;
  94688. }
  94689. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  94690. if (this.leftController) {
  94691. this.leftController._gazeTracker.material.emissiveColor = color;
  94692. }
  94693. if (this.rightController) {
  94694. this.rightController._gazeTracker.material.emissiveColor = color;
  94695. }
  94696. };
  94697. /**
  94698. * Exits VR and disposes of the vr experience helper
  94699. */
  94700. VRExperienceHelper.prototype.dispose = function () {
  94701. if (this.isInVRMode) {
  94702. this.exitVR();
  94703. }
  94704. if (this._postProcessMove) {
  94705. this._postProcessMove.dispose();
  94706. }
  94707. if (this._webVRCamera) {
  94708. this._webVRCamera.dispose();
  94709. }
  94710. if (this._vrDeviceOrientationCamera) {
  94711. this._vrDeviceOrientationCamera.dispose();
  94712. }
  94713. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  94714. document.body.removeChild(this._btnVR);
  94715. }
  94716. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  94717. this._deviceOrientationCamera.dispose();
  94718. }
  94719. if (this._cameraGazer) {
  94720. this._cameraGazer.dispose();
  94721. }
  94722. if (this.leftController) {
  94723. this.leftController.dispose();
  94724. }
  94725. if (this.rightController) {
  94726. this.rightController.dispose();
  94727. }
  94728. if (this._teleportationTarget) {
  94729. this._teleportationTarget.dispose();
  94730. }
  94731. this._floorMeshesCollection = [];
  94732. document.removeEventListener("keydown", this._onKeyDown);
  94733. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94734. window.removeEventListener("resize", this._onResize);
  94735. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  94736. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  94737. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  94738. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  94739. document.onmsfullscreenchange = null;
  94740. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  94741. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  94742. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  94743. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94744. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  94745. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  94746. this._scene.unregisterBeforeRender(this.beforeRender);
  94747. };
  94748. /**
  94749. * Gets the name of the VRExperienceHelper class
  94750. * @returns "VRExperienceHelper"
  94751. */
  94752. VRExperienceHelper.prototype.getClassName = function () {
  94753. return "VRExperienceHelper";
  94754. };
  94755. return VRExperienceHelper;
  94756. }());
  94757. BABYLON.VRExperienceHelper = VRExperienceHelper;
  94758. })(BABYLON || (BABYLON = {}));
  94759. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  94760. // Mainly based on these 2 articles :
  94761. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  94762. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  94763. var BABYLON;
  94764. (function (BABYLON) {
  94765. /**
  94766. * Defines the potential axis of a Joystick
  94767. */
  94768. var JoystickAxis;
  94769. (function (JoystickAxis) {
  94770. /** X axis */
  94771. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  94772. /** Y axis */
  94773. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  94774. /** Z axis */
  94775. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  94776. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  94777. /**
  94778. * Class used to define virtual joystick (used in touch mode)
  94779. */
  94780. var VirtualJoystick = /** @class */ (function () {
  94781. /**
  94782. * Creates a new virtual joystick
  94783. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94784. */
  94785. function VirtualJoystick(leftJoystick) {
  94786. var _this = this;
  94787. if (leftJoystick) {
  94788. this._leftJoystick = true;
  94789. }
  94790. else {
  94791. this._leftJoystick = false;
  94792. }
  94793. VirtualJoystick._globalJoystickIndex++;
  94794. // By default left & right arrow keys are moving the X
  94795. // and up & down keys are moving the Y
  94796. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94797. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94798. this.reverseLeftRight = false;
  94799. this.reverseUpDown = false;
  94800. // collections of pointers
  94801. this._touches = new BABYLON.StringDictionary();
  94802. this.deltaPosition = BABYLON.Vector3.Zero();
  94803. this._joystickSensibility = 25;
  94804. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94805. this._onResize = function (evt) {
  94806. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94807. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94808. if (VirtualJoystick.vjCanvas) {
  94809. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94810. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94811. }
  94812. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94813. };
  94814. // injecting a canvas element on top of the canvas 3D game
  94815. if (!VirtualJoystick.vjCanvas) {
  94816. window.addEventListener("resize", this._onResize, false);
  94817. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94818. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94819. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94820. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94821. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94822. VirtualJoystick.vjCanvas.style.width = "100%";
  94823. VirtualJoystick.vjCanvas.style.height = "100%";
  94824. VirtualJoystick.vjCanvas.style.position = "absolute";
  94825. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94826. VirtualJoystick.vjCanvas.style.top = "0px";
  94827. VirtualJoystick.vjCanvas.style.left = "0px";
  94828. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94829. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94830. // Support for jQuery PEP polyfill
  94831. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94832. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94833. if (!context) {
  94834. throw new Error("Unable to create canvas for virtual joystick");
  94835. }
  94836. VirtualJoystick.vjCanvasContext = context;
  94837. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94838. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94839. document.body.appendChild(VirtualJoystick.vjCanvas);
  94840. }
  94841. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94842. this.pressed = false;
  94843. // default joystick color
  94844. this._joystickColor = "cyan";
  94845. this._joystickPointerID = -1;
  94846. // current joystick position
  94847. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94848. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94849. // origin joystick position
  94850. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94851. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94852. this._onPointerDownHandlerRef = function (evt) {
  94853. _this._onPointerDown(evt);
  94854. };
  94855. this._onPointerMoveHandlerRef = function (evt) {
  94856. _this._onPointerMove(evt);
  94857. };
  94858. this._onPointerUpHandlerRef = function (evt) {
  94859. _this._onPointerUp(evt);
  94860. };
  94861. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94862. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94863. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94864. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94865. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94866. evt.preventDefault(); // Disables system menu
  94867. }, false);
  94868. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94869. }
  94870. /**
  94871. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94872. * @param newJoystickSensibility defines the new sensibility
  94873. */
  94874. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94875. this._joystickSensibility = newJoystickSensibility;
  94876. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94877. };
  94878. VirtualJoystick.prototype._onPointerDown = function (e) {
  94879. var positionOnScreenCondition;
  94880. e.preventDefault();
  94881. if (this._leftJoystick === true) {
  94882. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94883. }
  94884. else {
  94885. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94886. }
  94887. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94888. // First contact will be dedicated to the virtual joystick
  94889. this._joystickPointerID = e.pointerId;
  94890. this._joystickPointerStartPos.x = e.clientX;
  94891. this._joystickPointerStartPos.y = e.clientY;
  94892. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94893. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94894. this._deltaJoystickVector.x = 0;
  94895. this._deltaJoystickVector.y = 0;
  94896. this.pressed = true;
  94897. this._touches.add(e.pointerId.toString(), e);
  94898. }
  94899. else {
  94900. // You can only trigger the action buttons with a joystick declared
  94901. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94902. this._action();
  94903. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94904. }
  94905. }
  94906. };
  94907. VirtualJoystick.prototype._onPointerMove = function (e) {
  94908. // If the current pointer is the one associated to the joystick (first touch contact)
  94909. if (this._joystickPointerID == e.pointerId) {
  94910. this._joystickPointerPos.x = e.clientX;
  94911. this._joystickPointerPos.y = e.clientY;
  94912. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94913. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94914. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94915. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94916. switch (this._axisTargetedByLeftAndRight) {
  94917. case JoystickAxis.X:
  94918. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94919. break;
  94920. case JoystickAxis.Y:
  94921. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94922. break;
  94923. case JoystickAxis.Z:
  94924. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94925. break;
  94926. }
  94927. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94928. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94929. switch (this._axisTargetedByUpAndDown) {
  94930. case JoystickAxis.X:
  94931. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94932. break;
  94933. case JoystickAxis.Y:
  94934. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94935. break;
  94936. case JoystickAxis.Z:
  94937. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94938. break;
  94939. }
  94940. }
  94941. else {
  94942. var data = this._touches.get(e.pointerId.toString());
  94943. if (data) {
  94944. data.x = e.clientX;
  94945. data.y = e.clientY;
  94946. }
  94947. }
  94948. };
  94949. VirtualJoystick.prototype._onPointerUp = function (e) {
  94950. if (this._joystickPointerID == e.pointerId) {
  94951. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94952. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94953. this._joystickPointerID = -1;
  94954. this.pressed = false;
  94955. }
  94956. else {
  94957. var touch = this._touches.get(e.pointerId.toString());
  94958. if (touch) {
  94959. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94960. }
  94961. }
  94962. this._deltaJoystickVector.x = 0;
  94963. this._deltaJoystickVector.y = 0;
  94964. this._touches.remove(e.pointerId.toString());
  94965. };
  94966. /**
  94967. * Change the color of the virtual joystick
  94968. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94969. */
  94970. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94971. this._joystickColor = newColor;
  94972. };
  94973. /**
  94974. * Defines a callback to call when the joystick is touched
  94975. * @param action defines the callback
  94976. */
  94977. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94978. this._action = action;
  94979. };
  94980. /**
  94981. * Defines which axis you'd like to control for left & right
  94982. * @param axis defines the axis to use
  94983. */
  94984. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94985. switch (axis) {
  94986. case JoystickAxis.X:
  94987. case JoystickAxis.Y:
  94988. case JoystickAxis.Z:
  94989. this._axisTargetedByLeftAndRight = axis;
  94990. break;
  94991. default:
  94992. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94993. break;
  94994. }
  94995. };
  94996. /**
  94997. * Defines which axis you'd like to control for up & down
  94998. * @param axis defines the axis to use
  94999. */
  95000. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  95001. switch (axis) {
  95002. case JoystickAxis.X:
  95003. case JoystickAxis.Y:
  95004. case JoystickAxis.Z:
  95005. this._axisTargetedByUpAndDown = axis;
  95006. break;
  95007. default:
  95008. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95009. break;
  95010. }
  95011. };
  95012. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  95013. var _this = this;
  95014. if (this.pressed) {
  95015. this._touches.forEach(function (key, touch) {
  95016. if (touch.pointerId === _this._joystickPointerID) {
  95017. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  95018. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  95019. VirtualJoystick.vjCanvasContext.beginPath();
  95020. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95021. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95022. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  95023. VirtualJoystick.vjCanvasContext.stroke();
  95024. VirtualJoystick.vjCanvasContext.closePath();
  95025. VirtualJoystick.vjCanvasContext.beginPath();
  95026. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95027. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95028. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  95029. VirtualJoystick.vjCanvasContext.stroke();
  95030. VirtualJoystick.vjCanvasContext.closePath();
  95031. VirtualJoystick.vjCanvasContext.beginPath();
  95032. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95033. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  95034. VirtualJoystick.vjCanvasContext.stroke();
  95035. VirtualJoystick.vjCanvasContext.closePath();
  95036. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  95037. }
  95038. else {
  95039. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95040. VirtualJoystick.vjCanvasContext.beginPath();
  95041. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  95042. VirtualJoystick.vjCanvasContext.beginPath();
  95043. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  95044. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95045. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  95046. VirtualJoystick.vjCanvasContext.stroke();
  95047. VirtualJoystick.vjCanvasContext.closePath();
  95048. touch.prevX = touch.x;
  95049. touch.prevY = touch.y;
  95050. }
  95051. ;
  95052. });
  95053. }
  95054. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95055. };
  95056. /**
  95057. * Release internal HTML canvas
  95058. */
  95059. VirtualJoystick.prototype.releaseCanvas = function () {
  95060. if (VirtualJoystick.vjCanvas) {
  95061. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  95062. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  95063. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  95064. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  95065. window.removeEventListener("resize", this._onResize);
  95066. document.body.removeChild(VirtualJoystick.vjCanvas);
  95067. VirtualJoystick.vjCanvas = null;
  95068. }
  95069. };
  95070. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  95071. VirtualJoystick._globalJoystickIndex = 0;
  95072. return VirtualJoystick;
  95073. }());
  95074. BABYLON.VirtualJoystick = VirtualJoystick;
  95075. })(BABYLON || (BABYLON = {}));
  95076. //# sourceMappingURL=babylon.virtualJoystick.js.map
  95077. var BABYLON;
  95078. (function (BABYLON) {
  95079. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  95080. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  95081. });
  95082. // We're mainly based on the logic defined into the FreeCamera code
  95083. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  95084. __extends(VirtualJoysticksCamera, _super);
  95085. function VirtualJoysticksCamera(name, position, scene) {
  95086. var _this = _super.call(this, name, position, scene) || this;
  95087. _this.inputs.addVirtualJoystick();
  95088. return _this;
  95089. }
  95090. VirtualJoysticksCamera.prototype.getClassName = function () {
  95091. return "VirtualJoysticksCamera";
  95092. };
  95093. return VirtualJoysticksCamera;
  95094. }(BABYLON.FreeCamera));
  95095. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  95096. })(BABYLON || (BABYLON = {}));
  95097. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  95098. var BABYLON;
  95099. (function (BABYLON) {
  95100. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  95101. function FreeCameraVirtualJoystickInput() {
  95102. }
  95103. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  95104. return this._leftjoystick;
  95105. };
  95106. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  95107. return this._rightjoystick;
  95108. };
  95109. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  95110. if (this._leftjoystick) {
  95111. var camera = this.camera;
  95112. var speed = camera._computeLocalCameraSpeed() * 50;
  95113. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  95114. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  95115. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  95116. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  95117. if (!this._leftjoystick.pressed) {
  95118. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  95119. }
  95120. if (!this._rightjoystick.pressed) {
  95121. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  95122. }
  95123. }
  95124. };
  95125. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  95126. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  95127. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  95128. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  95129. this._leftjoystick.setJoystickSensibility(0.15);
  95130. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  95131. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  95132. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  95133. this._rightjoystick.reverseUpDown = true;
  95134. this._rightjoystick.setJoystickSensibility(0.05);
  95135. this._rightjoystick.setJoystickColor("yellow");
  95136. };
  95137. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  95138. this._leftjoystick.releaseCanvas();
  95139. this._rightjoystick.releaseCanvas();
  95140. };
  95141. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  95142. return "FreeCameraVirtualJoystickInput";
  95143. };
  95144. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  95145. return "virtualJoystick";
  95146. };
  95147. return FreeCameraVirtualJoystickInput;
  95148. }());
  95149. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  95150. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  95151. })(BABYLON || (BABYLON = {}));
  95152. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  95153. var BABYLON;
  95154. (function (BABYLON) {
  95155. var SimplificationSettings = /** @class */ (function () {
  95156. function SimplificationSettings(quality, distance, optimizeMesh) {
  95157. this.quality = quality;
  95158. this.distance = distance;
  95159. this.optimizeMesh = optimizeMesh;
  95160. }
  95161. return SimplificationSettings;
  95162. }());
  95163. BABYLON.SimplificationSettings = SimplificationSettings;
  95164. var SimplificationQueue = /** @class */ (function () {
  95165. function SimplificationQueue() {
  95166. this.running = false;
  95167. this._simplificationArray = [];
  95168. }
  95169. SimplificationQueue.prototype.addTask = function (task) {
  95170. this._simplificationArray.push(task);
  95171. };
  95172. SimplificationQueue.prototype.executeNext = function () {
  95173. var task = this._simplificationArray.pop();
  95174. if (task) {
  95175. this.running = true;
  95176. this.runSimplification(task);
  95177. }
  95178. else {
  95179. this.running = false;
  95180. }
  95181. };
  95182. SimplificationQueue.prototype.runSimplification = function (task) {
  95183. var _this = this;
  95184. if (task.parallelProcessing) {
  95185. //parallel simplifier
  95186. task.settings.forEach(function (setting) {
  95187. var simplifier = _this.getSimplifier(task);
  95188. simplifier.simplify(setting, function (newMesh) {
  95189. task.mesh.addLODLevel(setting.distance, newMesh);
  95190. newMesh.isVisible = true;
  95191. //check if it is the last
  95192. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  95193. //all done, run the success callback.
  95194. task.successCallback();
  95195. }
  95196. _this.executeNext();
  95197. });
  95198. });
  95199. }
  95200. else {
  95201. //single simplifier.
  95202. var simplifier = this.getSimplifier(task);
  95203. var runDecimation = function (setting, callback) {
  95204. simplifier.simplify(setting, function (newMesh) {
  95205. task.mesh.addLODLevel(setting.distance, newMesh);
  95206. newMesh.isVisible = true;
  95207. //run the next quality level
  95208. callback();
  95209. });
  95210. };
  95211. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  95212. runDecimation(task.settings[loop.index], function () {
  95213. loop.executeNext();
  95214. });
  95215. }, function () {
  95216. //execution ended, run the success callback.
  95217. if (task.successCallback) {
  95218. task.successCallback();
  95219. }
  95220. _this.executeNext();
  95221. });
  95222. }
  95223. };
  95224. SimplificationQueue.prototype.getSimplifier = function (task) {
  95225. switch (task.simplificationType) {
  95226. case SimplificationType.QUADRATIC:
  95227. default:
  95228. return new QuadraticErrorSimplification(task.mesh);
  95229. }
  95230. };
  95231. return SimplificationQueue;
  95232. }());
  95233. BABYLON.SimplificationQueue = SimplificationQueue;
  95234. /**
  95235. * The implemented types of simplification
  95236. * At the moment only Quadratic Error Decimation is implemented
  95237. */
  95238. var SimplificationType;
  95239. (function (SimplificationType) {
  95240. /** Quadratic error decimation */
  95241. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  95242. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  95243. var DecimationTriangle = /** @class */ (function () {
  95244. function DecimationTriangle(vertices) {
  95245. this.vertices = vertices;
  95246. this.error = new Array(4);
  95247. this.deleted = false;
  95248. this.isDirty = false;
  95249. this.deletePending = false;
  95250. this.borderFactor = 0;
  95251. }
  95252. return DecimationTriangle;
  95253. }());
  95254. BABYLON.DecimationTriangle = DecimationTriangle;
  95255. var DecimationVertex = /** @class */ (function () {
  95256. function DecimationVertex(position, id) {
  95257. this.position = position;
  95258. this.id = id;
  95259. this.isBorder = true;
  95260. this.q = new QuadraticMatrix();
  95261. this.triangleCount = 0;
  95262. this.triangleStart = 0;
  95263. this.originalOffsets = [];
  95264. }
  95265. DecimationVertex.prototype.updatePosition = function (newPosition) {
  95266. this.position.copyFrom(newPosition);
  95267. };
  95268. return DecimationVertex;
  95269. }());
  95270. BABYLON.DecimationVertex = DecimationVertex;
  95271. var QuadraticMatrix = /** @class */ (function () {
  95272. function QuadraticMatrix(data) {
  95273. this.data = new Array(10);
  95274. for (var i = 0; i < 10; ++i) {
  95275. if (data && data[i]) {
  95276. this.data[i] = data[i];
  95277. }
  95278. else {
  95279. this.data[i] = 0;
  95280. }
  95281. }
  95282. }
  95283. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  95284. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  95285. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  95286. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  95287. return det;
  95288. };
  95289. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  95290. for (var i = 0; i < 10; ++i) {
  95291. this.data[i] += matrix.data[i];
  95292. }
  95293. };
  95294. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  95295. for (var i = 0; i < 10; ++i) {
  95296. this.data[i] += data[i];
  95297. }
  95298. };
  95299. QuadraticMatrix.prototype.add = function (matrix) {
  95300. var m = new QuadraticMatrix();
  95301. for (var i = 0; i < 10; ++i) {
  95302. m.data[i] = this.data[i] + matrix.data[i];
  95303. }
  95304. return m;
  95305. };
  95306. QuadraticMatrix.FromData = function (a, b, c, d) {
  95307. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  95308. };
  95309. //returning an array to avoid garbage collection
  95310. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  95311. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  95312. };
  95313. return QuadraticMatrix;
  95314. }());
  95315. BABYLON.QuadraticMatrix = QuadraticMatrix;
  95316. var Reference = /** @class */ (function () {
  95317. function Reference(vertexId, triangleId) {
  95318. this.vertexId = vertexId;
  95319. this.triangleId = triangleId;
  95320. }
  95321. return Reference;
  95322. }());
  95323. BABYLON.Reference = Reference;
  95324. /**
  95325. * An implementation of the Quadratic Error simplification algorithm.
  95326. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  95327. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  95328. * @author RaananW
  95329. */
  95330. var QuadraticErrorSimplification = /** @class */ (function () {
  95331. function QuadraticErrorSimplification(_mesh) {
  95332. this._mesh = _mesh;
  95333. this.syncIterations = 5000;
  95334. this.aggressiveness = 7;
  95335. this.decimationIterations = 100;
  95336. this.boundingBoxEpsilon = BABYLON.Epsilon;
  95337. }
  95338. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  95339. var _this = this;
  95340. this.initDecimatedMesh();
  95341. //iterating through the submeshes array, one after the other.
  95342. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  95343. _this.initWithMesh(loop.index, function () {
  95344. _this.runDecimation(settings, loop.index, function () {
  95345. loop.executeNext();
  95346. });
  95347. }, settings.optimizeMesh);
  95348. }, function () {
  95349. setTimeout(function () {
  95350. successCallback(_this._reconstructedMesh);
  95351. }, 0);
  95352. });
  95353. };
  95354. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  95355. var _this = this;
  95356. var targetCount = ~~(this.triangles.length * settings.quality);
  95357. var deletedTriangles = 0;
  95358. var triangleCount = this.triangles.length;
  95359. var iterationFunction = function (iteration, callback) {
  95360. setTimeout(function () {
  95361. if (iteration % 5 === 0) {
  95362. _this.updateMesh(iteration === 0);
  95363. }
  95364. for (var i = 0; i < _this.triangles.length; ++i) {
  95365. _this.triangles[i].isDirty = false;
  95366. }
  95367. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  95368. var trianglesIterator = function (i) {
  95369. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  95370. var t = _this.triangles[tIdx];
  95371. if (!t)
  95372. return;
  95373. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  95374. return;
  95375. }
  95376. for (var j = 0; j < 3; ++j) {
  95377. if (t.error[j] < threshold) {
  95378. var deleted0 = [];
  95379. var deleted1 = [];
  95380. var v0 = t.vertices[j];
  95381. var v1 = t.vertices[(j + 1) % 3];
  95382. if (v0.isBorder || v1.isBorder)
  95383. continue;
  95384. var p = BABYLON.Vector3.Zero();
  95385. var n = BABYLON.Vector3.Zero();
  95386. var uv = BABYLON.Vector2.Zero();
  95387. var color = new BABYLON.Color4(0, 0, 0, 1);
  95388. _this.calculateError(v0, v1, p, n, uv, color);
  95389. var delTr = new Array();
  95390. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  95391. continue;
  95392. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  95393. continue;
  95394. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  95395. continue;
  95396. var uniqueArray = new Array();
  95397. delTr.forEach(function (deletedT) {
  95398. if (uniqueArray.indexOf(deletedT) === -1) {
  95399. deletedT.deletePending = true;
  95400. uniqueArray.push(deletedT);
  95401. }
  95402. });
  95403. if (uniqueArray.length % 2 !== 0) {
  95404. continue;
  95405. }
  95406. v0.q = v1.q.add(v0.q);
  95407. v0.updatePosition(p);
  95408. var tStart = _this.references.length;
  95409. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  95410. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  95411. var tCount = _this.references.length - tStart;
  95412. if (tCount <= v0.triangleCount) {
  95413. if (tCount) {
  95414. for (var c = 0; c < tCount; c++) {
  95415. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  95416. }
  95417. }
  95418. }
  95419. else {
  95420. v0.triangleStart = tStart;
  95421. }
  95422. v0.triangleCount = tCount;
  95423. break;
  95424. }
  95425. }
  95426. };
  95427. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  95428. }, 0);
  95429. };
  95430. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  95431. if (triangleCount - deletedTriangles <= targetCount)
  95432. loop.breakLoop();
  95433. else {
  95434. iterationFunction(loop.index, function () {
  95435. loop.executeNext();
  95436. });
  95437. }
  95438. }, function () {
  95439. setTimeout(function () {
  95440. //reconstruct this part of the mesh
  95441. _this.reconstructMesh(submeshIndex);
  95442. successCallback();
  95443. }, 0);
  95444. });
  95445. };
  95446. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  95447. var _this = this;
  95448. this.vertices = [];
  95449. this.triangles = [];
  95450. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95451. var indices = this._mesh.getIndices();
  95452. var submesh = this._mesh.subMeshes[submeshIndex];
  95453. var findInVertices = function (positionToSearch) {
  95454. if (optimizeMesh) {
  95455. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  95456. if (_this.vertices[ii].position.equals(positionToSearch)) {
  95457. return _this.vertices[ii];
  95458. }
  95459. }
  95460. }
  95461. return null;
  95462. };
  95463. var vertexReferences = [];
  95464. var vertexInit = function (i) {
  95465. if (!positionData) {
  95466. return;
  95467. }
  95468. var offset = i + submesh.verticesStart;
  95469. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  95470. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  95471. vertex.originalOffsets.push(offset);
  95472. if (vertex.id === _this.vertices.length) {
  95473. _this.vertices.push(vertex);
  95474. }
  95475. vertexReferences.push(vertex.id);
  95476. };
  95477. //var totalVertices = mesh.getTotalVertices();
  95478. var totalVertices = submesh.verticesCount;
  95479. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  95480. var indicesInit = function (i) {
  95481. if (!indices) {
  95482. return;
  95483. }
  95484. var offset = (submesh.indexStart / 3) + i;
  95485. var pos = (offset * 3);
  95486. var i0 = indices[pos + 0];
  95487. var i1 = indices[pos + 1];
  95488. var i2 = indices[pos + 2];
  95489. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  95490. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  95491. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  95492. var triangle = new DecimationTriangle([v0, v1, v2]);
  95493. triangle.originalOffset = pos;
  95494. _this.triangles.push(triangle);
  95495. };
  95496. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  95497. _this.init(callback);
  95498. });
  95499. });
  95500. };
  95501. QuadraticErrorSimplification.prototype.init = function (callback) {
  95502. var _this = this;
  95503. var triangleInit1 = function (i) {
  95504. var t = _this.triangles[i];
  95505. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  95506. for (var j = 0; j < 3; j++) {
  95507. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  95508. }
  95509. };
  95510. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  95511. var triangleInit2 = function (i) {
  95512. var t = _this.triangles[i];
  95513. for (var j = 0; j < 3; ++j) {
  95514. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  95515. }
  95516. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95517. };
  95518. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  95519. callback();
  95520. });
  95521. });
  95522. };
  95523. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  95524. var newTriangles = [];
  95525. var i;
  95526. for (i = 0; i < this.vertices.length; ++i) {
  95527. this.vertices[i].triangleCount = 0;
  95528. }
  95529. var t;
  95530. var j;
  95531. for (i = 0; i < this.triangles.length; ++i) {
  95532. if (!this.triangles[i].deleted) {
  95533. t = this.triangles[i];
  95534. for (j = 0; j < 3; ++j) {
  95535. t.vertices[j].triangleCount = 1;
  95536. }
  95537. newTriangles.push(t);
  95538. }
  95539. }
  95540. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  95541. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  95542. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  95543. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  95544. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  95545. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  95546. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  95547. var vertexCount = 0;
  95548. for (i = 0; i < this.vertices.length; ++i) {
  95549. var vertex = this.vertices[i];
  95550. vertex.id = vertexCount;
  95551. if (vertex.triangleCount) {
  95552. vertex.originalOffsets.forEach(function (originalOffset) {
  95553. if (!normalData) {
  95554. return;
  95555. }
  95556. newPositionData.push(vertex.position.x);
  95557. newPositionData.push(vertex.position.y);
  95558. newPositionData.push(vertex.position.z);
  95559. newNormalData.push(normalData[originalOffset * 3]);
  95560. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  95561. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  95562. if (uvs && uvs.length) {
  95563. newUVsData.push(uvs[(originalOffset * 2)]);
  95564. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  95565. }
  95566. else if (colorsData && colorsData.length) {
  95567. newColorsData.push(colorsData[(originalOffset * 4)]);
  95568. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  95569. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  95570. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  95571. }
  95572. ++vertexCount;
  95573. });
  95574. }
  95575. }
  95576. var startingIndex = this._reconstructedMesh.getTotalIndices();
  95577. var startingVertex = this._reconstructedMesh.getTotalVertices();
  95578. var submeshesArray = this._reconstructedMesh.subMeshes;
  95579. this._reconstructedMesh.subMeshes = [];
  95580. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  95581. var originalIndices = this._mesh.getIndices();
  95582. for (i = 0; i < newTriangles.length; ++i) {
  95583. t = newTriangles[i]; //now get the new referencing point for each vertex
  95584. [0, 1, 2].forEach(function (idx) {
  95585. var id = originalIndices[t.originalOffset + idx];
  95586. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  95587. if (offset < 0)
  95588. offset = 0;
  95589. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  95590. });
  95591. }
  95592. //overwriting the old vertex buffers and indices.
  95593. this._reconstructedMesh.setIndices(newIndicesArray);
  95594. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  95595. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  95596. if (newUVsData.length > 0)
  95597. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  95598. if (newColorsData.length > 0)
  95599. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  95600. //create submesh
  95601. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  95602. if (submeshIndex > 0) {
  95603. this._reconstructedMesh.subMeshes = [];
  95604. submeshesArray.forEach(function (submesh) {
  95605. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  95606. });
  95607. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  95608. }
  95609. };
  95610. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  95611. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  95612. this._reconstructedMesh.material = this._mesh.material;
  95613. this._reconstructedMesh.parent = this._mesh.parent;
  95614. this._reconstructedMesh.isVisible = false;
  95615. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  95616. };
  95617. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  95618. for (var i = 0; i < vertex1.triangleCount; ++i) {
  95619. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  95620. if (t.deleted)
  95621. continue;
  95622. var s = this.references[vertex1.triangleStart + i].vertexId;
  95623. var v1 = t.vertices[(s + 1) % 3];
  95624. var v2 = t.vertices[(s + 2) % 3];
  95625. if ((v1 === vertex2 || v2 === vertex2)) {
  95626. deletedArray[i] = true;
  95627. delTr.push(t);
  95628. continue;
  95629. }
  95630. var d1 = v1.position.subtract(point);
  95631. d1 = d1.normalize();
  95632. var d2 = v2.position.subtract(point);
  95633. d2 = d2.normalize();
  95634. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  95635. return true;
  95636. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  95637. deletedArray[i] = false;
  95638. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  95639. return true;
  95640. }
  95641. return false;
  95642. };
  95643. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  95644. var newDeleted = deletedTriangles;
  95645. for (var i = 0; i < vertex.triangleCount; ++i) {
  95646. var ref = this.references[vertex.triangleStart + i];
  95647. var t = this.triangles[ref.triangleId];
  95648. if (t.deleted)
  95649. continue;
  95650. if (deletedArray[i] && t.deletePending) {
  95651. t.deleted = true;
  95652. newDeleted++;
  95653. continue;
  95654. }
  95655. t.vertices[ref.vertexId] = origVertex;
  95656. t.isDirty = true;
  95657. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  95658. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  95659. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  95660. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95661. this.references.push(ref);
  95662. }
  95663. return newDeleted;
  95664. };
  95665. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  95666. for (var i = 0; i < this.vertices.length; ++i) {
  95667. var vCount = [];
  95668. var vId = [];
  95669. var v = this.vertices[i];
  95670. var j;
  95671. for (j = 0; j < v.triangleCount; ++j) {
  95672. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  95673. for (var ii = 0; ii < 3; ii++) {
  95674. var ofs = 0;
  95675. var vv = triangle.vertices[ii];
  95676. while (ofs < vCount.length) {
  95677. if (vId[ofs] === vv.id)
  95678. break;
  95679. ++ofs;
  95680. }
  95681. if (ofs === vCount.length) {
  95682. vCount.push(1);
  95683. vId.push(vv.id);
  95684. }
  95685. else {
  95686. vCount[ofs]++;
  95687. }
  95688. }
  95689. }
  95690. for (j = 0; j < vCount.length; ++j) {
  95691. if (vCount[j] === 1) {
  95692. this.vertices[vId[j]].isBorder = true;
  95693. }
  95694. else {
  95695. this.vertices[vId[j]].isBorder = false;
  95696. }
  95697. }
  95698. }
  95699. };
  95700. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  95701. if (identifyBorders === void 0) { identifyBorders = false; }
  95702. var i;
  95703. if (!identifyBorders) {
  95704. var newTrianglesVector = [];
  95705. for (i = 0; i < this.triangles.length; ++i) {
  95706. if (!this.triangles[i].deleted) {
  95707. newTrianglesVector.push(this.triangles[i]);
  95708. }
  95709. }
  95710. this.triangles = newTrianglesVector;
  95711. }
  95712. for (i = 0; i < this.vertices.length; ++i) {
  95713. this.vertices[i].triangleCount = 0;
  95714. this.vertices[i].triangleStart = 0;
  95715. }
  95716. var t;
  95717. var j;
  95718. var v;
  95719. for (i = 0; i < this.triangles.length; ++i) {
  95720. t = this.triangles[i];
  95721. for (j = 0; j < 3; ++j) {
  95722. v = t.vertices[j];
  95723. v.triangleCount++;
  95724. }
  95725. }
  95726. var tStart = 0;
  95727. for (i = 0; i < this.vertices.length; ++i) {
  95728. this.vertices[i].triangleStart = tStart;
  95729. tStart += this.vertices[i].triangleCount;
  95730. this.vertices[i].triangleCount = 0;
  95731. }
  95732. var newReferences = new Array(this.triangles.length * 3);
  95733. for (i = 0; i < this.triangles.length; ++i) {
  95734. t = this.triangles[i];
  95735. for (j = 0; j < 3; ++j) {
  95736. v = t.vertices[j];
  95737. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  95738. v.triangleCount++;
  95739. }
  95740. }
  95741. this.references = newReferences;
  95742. if (identifyBorders) {
  95743. this.identifyBorder();
  95744. }
  95745. };
  95746. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  95747. var x = point.x;
  95748. var y = point.y;
  95749. var z = point.z;
  95750. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  95751. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  95752. };
  95753. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  95754. var q = vertex1.q.add(vertex2.q);
  95755. var border = vertex1.isBorder && vertex2.isBorder;
  95756. var error = 0;
  95757. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  95758. if (qDet !== 0 && !border) {
  95759. if (!pointResult) {
  95760. pointResult = BABYLON.Vector3.Zero();
  95761. }
  95762. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  95763. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  95764. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  95765. error = this.vertexError(q, pointResult);
  95766. }
  95767. else {
  95768. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  95769. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  95770. var error1 = this.vertexError(q, vertex1.position);
  95771. var error2 = this.vertexError(q, vertex2.position);
  95772. var error3 = this.vertexError(q, p3);
  95773. error = Math.min(error1, error2, error3);
  95774. if (error === error1) {
  95775. if (pointResult) {
  95776. pointResult.copyFrom(vertex1.position);
  95777. }
  95778. }
  95779. else if (error === error2) {
  95780. if (pointResult) {
  95781. pointResult.copyFrom(vertex2.position);
  95782. }
  95783. }
  95784. else {
  95785. if (pointResult) {
  95786. pointResult.copyFrom(p3);
  95787. }
  95788. }
  95789. }
  95790. return error;
  95791. };
  95792. return QuadraticErrorSimplification;
  95793. }());
  95794. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95795. })(BABYLON || (BABYLON = {}));
  95796. //# sourceMappingURL=babylon.meshSimplification.js.map
  95797. var BABYLON;
  95798. (function (BABYLON) {
  95799. var MeshLODLevel = /** @class */ (function () {
  95800. function MeshLODLevel(distance, mesh) {
  95801. this.distance = distance;
  95802. this.mesh = mesh;
  95803. }
  95804. return MeshLODLevel;
  95805. }());
  95806. BABYLON.MeshLODLevel = MeshLODLevel;
  95807. })(BABYLON || (BABYLON = {}));
  95808. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95809. var BABYLON;
  95810. (function (BABYLON) {
  95811. /**
  95812. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95813. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95814. */
  95815. var SceneOptimization = /** @class */ (function () {
  95816. /**
  95817. * Creates the SceneOptimization object
  95818. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95819. * @param desc defines the description associated with the optimization
  95820. */
  95821. function SceneOptimization(
  95822. /**
  95823. * Defines the priority of this optimization (0 by default which means first in the list)
  95824. */
  95825. priority) {
  95826. if (priority === void 0) { priority = 0; }
  95827. this.priority = priority;
  95828. }
  95829. /**
  95830. * Gets a string describing the action executed by the current optimization
  95831. * @returns description string
  95832. */
  95833. SceneOptimization.prototype.getDescription = function () {
  95834. return "";
  95835. };
  95836. /**
  95837. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95838. * @param scene defines the current scene where to apply this optimization
  95839. * @param optimizer defines the current optimizer
  95840. * @returns true if everything that can be done was applied
  95841. */
  95842. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95843. return true;
  95844. };
  95845. ;
  95846. return SceneOptimization;
  95847. }());
  95848. BABYLON.SceneOptimization = SceneOptimization;
  95849. /**
  95850. * Defines an optimization used to reduce the size of render target textures
  95851. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95852. */
  95853. var TextureOptimization = /** @class */ (function (_super) {
  95854. __extends(TextureOptimization, _super);
  95855. /**
  95856. * Creates the TextureOptimization object
  95857. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95858. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  95859. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95860. */
  95861. function TextureOptimization(
  95862. /**
  95863. * Defines the priority of this optimization (0 by default which means first in the list)
  95864. */
  95865. priority,
  95866. /**
  95867. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  95868. */
  95869. maximumSize,
  95870. /**
  95871. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95872. */
  95873. step) {
  95874. if (priority === void 0) { priority = 0; }
  95875. if (maximumSize === void 0) { maximumSize = 1024; }
  95876. if (step === void 0) { step = 0.5; }
  95877. var _this = _super.call(this, priority) || this;
  95878. _this.priority = priority;
  95879. _this.maximumSize = maximumSize;
  95880. _this.step = step;
  95881. return _this;
  95882. }
  95883. /**
  95884. * Gets a string describing the action executed by the current optimization
  95885. * @returns description string
  95886. */
  95887. TextureOptimization.prototype.getDescription = function () {
  95888. return "Reducing render target texture size to " + this.maximumSize;
  95889. };
  95890. /**
  95891. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95892. * @param scene defines the current scene where to apply this optimization
  95893. * @param optimizer defines the current optimizer
  95894. * @returns true if everything that can be done was applied
  95895. */
  95896. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95897. var allDone = true;
  95898. for (var index = 0; index < scene.textures.length; index++) {
  95899. var texture = scene.textures[index];
  95900. if (!texture.canRescale || texture.getContext) {
  95901. continue;
  95902. }
  95903. var currentSize = texture.getSize();
  95904. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95905. if (maxDimension > this.maximumSize) {
  95906. texture.scale(this.step);
  95907. allDone = false;
  95908. }
  95909. }
  95910. return allDone;
  95911. };
  95912. return TextureOptimization;
  95913. }(SceneOptimization));
  95914. BABYLON.TextureOptimization = TextureOptimization;
  95915. /**
  95916. * Defines an optimization used to increase or decrease the rendering resolution
  95917. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95918. */
  95919. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95920. __extends(HardwareScalingOptimization, _super);
  95921. /**
  95922. * Creates the HardwareScalingOptimization object
  95923. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95924. * @param maximumScale defines the maximum scale to use (2 by default)
  95925. * @param step defines the step to use between two passes (0.5 by default)
  95926. */
  95927. function HardwareScalingOptimization(
  95928. /**
  95929. * Defines the priority of this optimization (0 by default which means first in the list)
  95930. */
  95931. priority,
  95932. /**
  95933. * Defines the maximum scale to use (2 by default)
  95934. */
  95935. maximumScale,
  95936. /**
  95937. * Defines the step to use between two passes (0.5 by default)
  95938. */
  95939. step) {
  95940. if (priority === void 0) { priority = 0; }
  95941. if (maximumScale === void 0) { maximumScale = 2; }
  95942. if (step === void 0) { step = 0.25; }
  95943. var _this = _super.call(this, priority) || this;
  95944. _this.priority = priority;
  95945. _this.maximumScale = maximumScale;
  95946. _this.step = step;
  95947. _this._currentScale = -1;
  95948. _this._directionOffset = 1;
  95949. return _this;
  95950. }
  95951. /**
  95952. * Gets a string describing the action executed by the current optimization
  95953. * @return description string
  95954. */
  95955. HardwareScalingOptimization.prototype.getDescription = function () {
  95956. return "Setting hardware scaling level to " + this._currentScale;
  95957. };
  95958. /**
  95959. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95960. * @param scene defines the current scene where to apply this optimization
  95961. * @param optimizer defines the current optimizer
  95962. * @returns true if everything that can be done was applied
  95963. */
  95964. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95965. if (this._currentScale === -1) {
  95966. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95967. if (this._currentScale > this.maximumScale) {
  95968. this._directionOffset = -1;
  95969. }
  95970. }
  95971. this._currentScale += this._directionOffset * this.step;
  95972. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95973. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95974. };
  95975. ;
  95976. return HardwareScalingOptimization;
  95977. }(SceneOptimization));
  95978. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95979. /**
  95980. * Defines an optimization used to remove shadows
  95981. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95982. */
  95983. var ShadowsOptimization = /** @class */ (function (_super) {
  95984. __extends(ShadowsOptimization, _super);
  95985. function ShadowsOptimization() {
  95986. return _super !== null && _super.apply(this, arguments) || this;
  95987. }
  95988. /**
  95989. * Gets a string describing the action executed by the current optimization
  95990. * @return description string
  95991. */
  95992. ShadowsOptimization.prototype.getDescription = function () {
  95993. return "Turning shadows on/off";
  95994. };
  95995. /**
  95996. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95997. * @param scene defines the current scene where to apply this optimization
  95998. * @param optimizer defines the current optimizer
  95999. * @returns true if everything that can be done was applied
  96000. */
  96001. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  96002. scene.shadowsEnabled = optimizer.isInImprovementMode;
  96003. return true;
  96004. };
  96005. ;
  96006. return ShadowsOptimization;
  96007. }(SceneOptimization));
  96008. BABYLON.ShadowsOptimization = ShadowsOptimization;
  96009. /**
  96010. * Defines an optimization used to turn post-processes off
  96011. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96012. */
  96013. var PostProcessesOptimization = /** @class */ (function (_super) {
  96014. __extends(PostProcessesOptimization, _super);
  96015. function PostProcessesOptimization() {
  96016. return _super !== null && _super.apply(this, arguments) || this;
  96017. }
  96018. /**
  96019. * Gets a string describing the action executed by the current optimization
  96020. * @return description string
  96021. */
  96022. PostProcessesOptimization.prototype.getDescription = function () {
  96023. return "Turning post-processes on/off";
  96024. };
  96025. /**
  96026. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96027. * @param scene defines the current scene where to apply this optimization
  96028. * @param optimizer defines the current optimizer
  96029. * @returns true if everything that can be done was applied
  96030. */
  96031. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  96032. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  96033. return true;
  96034. };
  96035. ;
  96036. return PostProcessesOptimization;
  96037. }(SceneOptimization));
  96038. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  96039. /**
  96040. * Defines an optimization used to turn lens flares off
  96041. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96042. */
  96043. var LensFlaresOptimization = /** @class */ (function (_super) {
  96044. __extends(LensFlaresOptimization, _super);
  96045. function LensFlaresOptimization() {
  96046. return _super !== null && _super.apply(this, arguments) || this;
  96047. }
  96048. /**
  96049. * Gets a string describing the action executed by the current optimization
  96050. * @return description string
  96051. */
  96052. LensFlaresOptimization.prototype.getDescription = function () {
  96053. return "Turning lens flares on/off";
  96054. };
  96055. /**
  96056. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96057. * @param scene defines the current scene where to apply this optimization
  96058. * @param optimizer defines the current optimizer
  96059. * @returns true if everything that can be done was applied
  96060. */
  96061. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  96062. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  96063. return true;
  96064. };
  96065. ;
  96066. return LensFlaresOptimization;
  96067. }(SceneOptimization));
  96068. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  96069. /**
  96070. * Defines an optimization based on user defined callback.
  96071. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96072. */
  96073. var CustomOptimization = /** @class */ (function (_super) {
  96074. __extends(CustomOptimization, _super);
  96075. function CustomOptimization() {
  96076. return _super !== null && _super.apply(this, arguments) || this;
  96077. }
  96078. /**
  96079. * Gets a string describing the action executed by the current optimization
  96080. * @returns description string
  96081. */
  96082. CustomOptimization.prototype.getDescription = function () {
  96083. if (this.onGetDescription) {
  96084. return this.onGetDescription();
  96085. }
  96086. return "Running user defined callback";
  96087. };
  96088. /**
  96089. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96090. * @param scene defines the current scene where to apply this optimization
  96091. * @param optimizer defines the current optimizer
  96092. * @returns true if everything that can be done was applied
  96093. */
  96094. CustomOptimization.prototype.apply = function (scene, optimizer) {
  96095. if (this.onApply) {
  96096. return this.onApply(scene, optimizer);
  96097. }
  96098. return true;
  96099. };
  96100. ;
  96101. return CustomOptimization;
  96102. }(SceneOptimization));
  96103. BABYLON.CustomOptimization = CustomOptimization;
  96104. /**
  96105. * Defines an optimization used to turn particles off
  96106. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96107. */
  96108. var ParticlesOptimization = /** @class */ (function (_super) {
  96109. __extends(ParticlesOptimization, _super);
  96110. function ParticlesOptimization() {
  96111. return _super !== null && _super.apply(this, arguments) || this;
  96112. }
  96113. /**
  96114. * Gets a string describing the action executed by the current optimization
  96115. * @return description string
  96116. */
  96117. ParticlesOptimization.prototype.getDescription = function () {
  96118. return "Turning particles on/off";
  96119. };
  96120. /**
  96121. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96122. * @param scene defines the current scene where to apply this optimization
  96123. * @param optimizer defines the current optimizer
  96124. * @returns true if everything that can be done was applied
  96125. */
  96126. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  96127. scene.particlesEnabled = optimizer.isInImprovementMode;
  96128. return true;
  96129. };
  96130. ;
  96131. return ParticlesOptimization;
  96132. }(SceneOptimization));
  96133. BABYLON.ParticlesOptimization = ParticlesOptimization;
  96134. /**
  96135. * Defines an optimization used to turn render targets off
  96136. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96137. */
  96138. var RenderTargetsOptimization = /** @class */ (function (_super) {
  96139. __extends(RenderTargetsOptimization, _super);
  96140. function RenderTargetsOptimization() {
  96141. return _super !== null && _super.apply(this, arguments) || this;
  96142. }
  96143. /**
  96144. * Gets a string describing the action executed by the current optimization
  96145. * @return description string
  96146. */
  96147. RenderTargetsOptimization.prototype.getDescription = function () {
  96148. return "Turning render targets off";
  96149. };
  96150. /**
  96151. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96152. * @param scene defines the current scene where to apply this optimization
  96153. * @param optimizer defines the current optimizer
  96154. * @returns true if everything that can be done was applied
  96155. */
  96156. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  96157. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  96158. return true;
  96159. };
  96160. ;
  96161. return RenderTargetsOptimization;
  96162. }(SceneOptimization));
  96163. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  96164. /**
  96165. * Defines an optimization used to merge meshes with compatible materials
  96166. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96167. */
  96168. var MergeMeshesOptimization = /** @class */ (function (_super) {
  96169. __extends(MergeMeshesOptimization, _super);
  96170. function MergeMeshesOptimization() {
  96171. var _this = _super !== null && _super.apply(this, arguments) || this;
  96172. _this._canBeMerged = function (abstractMesh) {
  96173. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  96174. return false;
  96175. }
  96176. var mesh = abstractMesh;
  96177. if (mesh.isDisposed()) {
  96178. return false;
  96179. }
  96180. if (!mesh.isVisible || !mesh.isEnabled()) {
  96181. return false;
  96182. }
  96183. if (mesh.instances.length > 0) {
  96184. return false;
  96185. }
  96186. if (mesh.skeleton || mesh.hasLODLevels) {
  96187. return false;
  96188. }
  96189. return true;
  96190. };
  96191. return _this;
  96192. }
  96193. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  96194. /**
  96195. * Gets or sets a boolean which defines if optimization octree has to be updated
  96196. */
  96197. get: function () {
  96198. return MergeMeshesOptimization._UpdateSelectionTree;
  96199. },
  96200. /**
  96201. * Gets or sets a boolean which defines if optimization octree has to be updated
  96202. */
  96203. set: function (value) {
  96204. MergeMeshesOptimization._UpdateSelectionTree = value;
  96205. },
  96206. enumerable: true,
  96207. configurable: true
  96208. });
  96209. /**
  96210. * Gets a string describing the action executed by the current optimization
  96211. * @return description string
  96212. */
  96213. MergeMeshesOptimization.prototype.getDescription = function () {
  96214. return "Merging similar meshes together";
  96215. };
  96216. /**
  96217. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96218. * @param scene defines the current scene where to apply this optimization
  96219. * @param optimizer defines the current optimizer
  96220. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  96221. * @returns true if everything that can be done was applied
  96222. */
  96223. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  96224. var globalPool = scene.meshes.slice(0);
  96225. var globalLength = globalPool.length;
  96226. for (var index = 0; index < globalLength; index++) {
  96227. var currentPool = new Array();
  96228. var current = globalPool[index];
  96229. // Checks
  96230. if (!this._canBeMerged(current)) {
  96231. continue;
  96232. }
  96233. currentPool.push(current);
  96234. // Find compatible meshes
  96235. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  96236. var otherMesh = globalPool[subIndex];
  96237. if (!this._canBeMerged(otherMesh)) {
  96238. continue;
  96239. }
  96240. if (otherMesh.material !== current.material) {
  96241. continue;
  96242. }
  96243. if (otherMesh.checkCollisions !== current.checkCollisions) {
  96244. continue;
  96245. }
  96246. currentPool.push(otherMesh);
  96247. globalLength--;
  96248. globalPool.splice(subIndex, 1);
  96249. subIndex--;
  96250. }
  96251. if (currentPool.length < 2) {
  96252. continue;
  96253. }
  96254. // Merge meshes
  96255. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  96256. }
  96257. if (updateSelectionTree != undefined) {
  96258. if (updateSelectionTree) {
  96259. scene.createOrUpdateSelectionOctree();
  96260. }
  96261. }
  96262. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  96263. scene.createOrUpdateSelectionOctree();
  96264. }
  96265. return true;
  96266. };
  96267. ;
  96268. MergeMeshesOptimization._UpdateSelectionTree = false;
  96269. return MergeMeshesOptimization;
  96270. }(SceneOptimization));
  96271. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  96272. /**
  96273. * Defines a list of options used by SceneOptimizer
  96274. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96275. */
  96276. var SceneOptimizerOptions = /** @class */ (function () {
  96277. /**
  96278. * Creates a new list of options used by SceneOptimizer
  96279. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  96280. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  96281. */
  96282. function SceneOptimizerOptions(
  96283. /**
  96284. * Defines the target frame rate to reach (60 by default)
  96285. */
  96286. targetFrameRate,
  96287. /**
  96288. * Defines the interval between two checkes (2000ms by default)
  96289. */
  96290. trackerDuration) {
  96291. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  96292. if (trackerDuration === void 0) { trackerDuration = 2000; }
  96293. this.targetFrameRate = targetFrameRate;
  96294. this.trackerDuration = trackerDuration;
  96295. /**
  96296. * Gets the list of optimizations to apply
  96297. */
  96298. this.optimizations = new Array();
  96299. }
  96300. /**
  96301. * Add a new optimization
  96302. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  96303. * @returns the current SceneOptimizerOptions
  96304. */
  96305. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  96306. this.optimizations.push(optimization);
  96307. return this;
  96308. };
  96309. /**
  96310. * Add a new custom optimization
  96311. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  96312. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  96313. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96314. * @returns the current SceneOptimizerOptions
  96315. */
  96316. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  96317. if (priority === void 0) { priority = 0; }
  96318. var optimization = new CustomOptimization(priority);
  96319. optimization.onApply = onApply;
  96320. optimization.onGetDescription = onGetDescription;
  96321. this.optimizations.push(optimization);
  96322. return this;
  96323. };
  96324. /**
  96325. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  96326. * @param targetFrameRate defines the target frame rate (60 by default)
  96327. * @returns a SceneOptimizerOptions object
  96328. */
  96329. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  96330. var result = new SceneOptimizerOptions(targetFrameRate);
  96331. var priority = 0;
  96332. result.addOptimization(new MergeMeshesOptimization(priority));
  96333. result.addOptimization(new ShadowsOptimization(priority));
  96334. result.addOptimization(new LensFlaresOptimization(priority));
  96335. // Next priority
  96336. priority++;
  96337. result.addOptimization(new PostProcessesOptimization(priority));
  96338. result.addOptimization(new ParticlesOptimization(priority));
  96339. // Next priority
  96340. priority++;
  96341. result.addOptimization(new TextureOptimization(priority, 1024));
  96342. return result;
  96343. };
  96344. /**
  96345. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  96346. * @param targetFrameRate defines the target frame rate (60 by default)
  96347. * @returns a SceneOptimizerOptions object
  96348. */
  96349. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  96350. var result = new SceneOptimizerOptions(targetFrameRate);
  96351. var priority = 0;
  96352. result.addOptimization(new MergeMeshesOptimization(priority));
  96353. result.addOptimization(new ShadowsOptimization(priority));
  96354. result.addOptimization(new LensFlaresOptimization(priority));
  96355. // Next priority
  96356. priority++;
  96357. result.addOptimization(new PostProcessesOptimization(priority));
  96358. result.addOptimization(new ParticlesOptimization(priority));
  96359. // Next priority
  96360. priority++;
  96361. result.addOptimization(new TextureOptimization(priority, 512));
  96362. // Next priority
  96363. priority++;
  96364. result.addOptimization(new RenderTargetsOptimization(priority));
  96365. // Next priority
  96366. priority++;
  96367. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  96368. return result;
  96369. };
  96370. /**
  96371. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  96372. * @param targetFrameRate defines the target frame rate (60 by default)
  96373. * @returns a SceneOptimizerOptions object
  96374. */
  96375. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  96376. var result = new SceneOptimizerOptions(targetFrameRate);
  96377. var priority = 0;
  96378. result.addOptimization(new MergeMeshesOptimization(priority));
  96379. result.addOptimization(new ShadowsOptimization(priority));
  96380. result.addOptimization(new LensFlaresOptimization(priority));
  96381. // Next priority
  96382. priority++;
  96383. result.addOptimization(new PostProcessesOptimization(priority));
  96384. result.addOptimization(new ParticlesOptimization(priority));
  96385. // Next priority
  96386. priority++;
  96387. result.addOptimization(new TextureOptimization(priority, 256));
  96388. // Next priority
  96389. priority++;
  96390. result.addOptimization(new RenderTargetsOptimization(priority));
  96391. // Next priority
  96392. priority++;
  96393. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  96394. return result;
  96395. };
  96396. return SceneOptimizerOptions;
  96397. }());
  96398. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  96399. /**
  96400. * Class used to run optimizations in order to reach a target frame rate
  96401. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96402. */
  96403. var SceneOptimizer = /** @class */ (function () {
  96404. /**
  96405. * Creates a new SceneOptimizer
  96406. * @param scene defines the scene to work on
  96407. * @param options defines the options to use with the SceneOptimizer
  96408. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  96409. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  96410. */
  96411. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  96412. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  96413. if (improvementMode === void 0) { improvementMode = false; }
  96414. var _this = this;
  96415. this._isRunning = false;
  96416. this._currentPriorityLevel = 0;
  96417. this._targetFrameRate = 60;
  96418. this._trackerDuration = 2000;
  96419. this._currentFrameRate = 0;
  96420. this._improvementMode = false;
  96421. /**
  96422. * Defines an observable called when the optimizer reaches the target frame rate
  96423. */
  96424. this.onSuccessObservable = new BABYLON.Observable();
  96425. /**
  96426. * Defines an observable called when the optimizer enables an optimization
  96427. */
  96428. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  96429. /**
  96430. * Defines an observable called when the optimizer is not able to reach the target frame rate
  96431. */
  96432. this.onFailureObservable = new BABYLON.Observable();
  96433. if (!options) {
  96434. this._options = new SceneOptimizerOptions();
  96435. }
  96436. else {
  96437. this._options = options;
  96438. }
  96439. if (this._options.targetFrameRate) {
  96440. this._targetFrameRate = this._options.targetFrameRate;
  96441. }
  96442. if (this._options.trackerDuration) {
  96443. this._trackerDuration = this._options.trackerDuration;
  96444. }
  96445. if (autoGeneratePriorities) {
  96446. var priority = 0;
  96447. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  96448. var optim = _a[_i];
  96449. optim.priority = priority++;
  96450. }
  96451. }
  96452. this._improvementMode = improvementMode;
  96453. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96454. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  96455. _this._sceneDisposeObserver = null;
  96456. _this.dispose();
  96457. });
  96458. }
  96459. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  96460. /**
  96461. * Gets a boolean indicating if the optimizer is in improvement mode
  96462. */
  96463. get: function () {
  96464. return this._improvementMode;
  96465. },
  96466. enumerable: true,
  96467. configurable: true
  96468. });
  96469. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  96470. /**
  96471. * Gets the current priority level (0 at start)
  96472. */
  96473. get: function () {
  96474. return this._currentPriorityLevel;
  96475. },
  96476. enumerable: true,
  96477. configurable: true
  96478. });
  96479. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  96480. /**
  96481. * Gets the current frame rate checked by the SceneOptimizer
  96482. */
  96483. get: function () {
  96484. return this._currentFrameRate;
  96485. },
  96486. enumerable: true,
  96487. configurable: true
  96488. });
  96489. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  96490. /**
  96491. * Gets or sets the current target frame rate (60 by default)
  96492. */
  96493. get: function () {
  96494. return this._targetFrameRate;
  96495. },
  96496. /**
  96497. * Gets or sets the current target frame rate (60 by default)
  96498. */
  96499. set: function (value) {
  96500. this._targetFrameRate = value;
  96501. },
  96502. enumerable: true,
  96503. configurable: true
  96504. });
  96505. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  96506. /**
  96507. * Gets or sets the current interval between two checks (every 2000ms by default)
  96508. */
  96509. get: function () {
  96510. return this._trackerDuration;
  96511. },
  96512. /**
  96513. * Gets or sets the current interval between two checks (every 2000ms by default)
  96514. */
  96515. set: function (value) {
  96516. this._trackerDuration = value;
  96517. },
  96518. enumerable: true,
  96519. configurable: true
  96520. });
  96521. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  96522. /**
  96523. * Gets the list of active optimizations
  96524. */
  96525. get: function () {
  96526. return this._options.optimizations;
  96527. },
  96528. enumerable: true,
  96529. configurable: true
  96530. });
  96531. /**
  96532. * Stops the current optimizer
  96533. */
  96534. SceneOptimizer.prototype.stop = function () {
  96535. this._isRunning = false;
  96536. };
  96537. /**
  96538. * Reset the optimizer to initial step (current priority level = 0)
  96539. */
  96540. SceneOptimizer.prototype.reset = function () {
  96541. this._currentPriorityLevel = 0;
  96542. };
  96543. /**
  96544. * Start the optimizer. By default it will try to reach a specific framerate
  96545. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  96546. */
  96547. SceneOptimizer.prototype.start = function () {
  96548. var _this = this;
  96549. if (this._isRunning) {
  96550. return;
  96551. }
  96552. this._isRunning = true;
  96553. // Let's wait for the scene to be ready before running our check
  96554. this._scene.executeWhenReady(function () {
  96555. setTimeout(function () {
  96556. _this._checkCurrentState();
  96557. }, _this._trackerDuration);
  96558. });
  96559. };
  96560. SceneOptimizer.prototype._checkCurrentState = function () {
  96561. var _this = this;
  96562. if (!this._isRunning) {
  96563. return;
  96564. }
  96565. var scene = this._scene;
  96566. var options = this._options;
  96567. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  96568. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  96569. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  96570. this._isRunning = false;
  96571. this.onSuccessObservable.notifyObservers(this);
  96572. return;
  96573. }
  96574. // Apply current level of optimizations
  96575. var allDone = true;
  96576. var noOptimizationApplied = true;
  96577. for (var index = 0; index < options.optimizations.length; index++) {
  96578. var optimization = options.optimizations[index];
  96579. if (optimization.priority === this._currentPriorityLevel) {
  96580. noOptimizationApplied = false;
  96581. allDone = allDone && optimization.apply(scene, this);
  96582. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  96583. }
  96584. }
  96585. // If no optimization was applied, this is a failure :(
  96586. if (noOptimizationApplied) {
  96587. this._isRunning = false;
  96588. this.onFailureObservable.notifyObservers(this);
  96589. return;
  96590. }
  96591. // If all optimizations were done, move to next level
  96592. if (allDone) {
  96593. this._currentPriorityLevel++;
  96594. }
  96595. // Let's the system running for a specific amount of time before checking FPS
  96596. scene.executeWhenReady(function () {
  96597. setTimeout(function () {
  96598. _this._checkCurrentState();
  96599. }, _this._trackerDuration);
  96600. });
  96601. };
  96602. /**
  96603. * Release all resources
  96604. */
  96605. SceneOptimizer.prototype.dispose = function () {
  96606. this.stop();
  96607. this.onSuccessObservable.clear();
  96608. this.onFailureObservable.clear();
  96609. this.onNewOptimizationAppliedObservable.clear();
  96610. if (this._sceneDisposeObserver) {
  96611. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96612. }
  96613. };
  96614. /**
  96615. * Helper function to create a SceneOptimizer with one single line of code
  96616. * @param scene defines the scene to work on
  96617. * @param options defines the options to use with the SceneOptimizer
  96618. * @param onSuccess defines a callback to call on success
  96619. * @param onFailure defines a callback to call on failure
  96620. * @returns the new SceneOptimizer object
  96621. */
  96622. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  96623. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  96624. if (onSuccess) {
  96625. optimizer.onSuccessObservable.add(function () {
  96626. onSuccess();
  96627. });
  96628. }
  96629. if (onFailure) {
  96630. optimizer.onFailureObservable.add(function () {
  96631. onFailure();
  96632. });
  96633. }
  96634. optimizer.start();
  96635. return optimizer;
  96636. };
  96637. return SceneOptimizer;
  96638. }());
  96639. BABYLON.SceneOptimizer = SceneOptimizer;
  96640. })(BABYLON || (BABYLON = {}));
  96641. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  96642. var BABYLON;
  96643. (function (BABYLON) {
  96644. var OutlineRenderer = /** @class */ (function () {
  96645. function OutlineRenderer(scene) {
  96646. this.zOffset = 1;
  96647. this._scene = scene;
  96648. }
  96649. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  96650. var _this = this;
  96651. if (useOverlay === void 0) { useOverlay = false; }
  96652. var scene = this._scene;
  96653. var engine = this._scene.getEngine();
  96654. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96655. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  96656. return;
  96657. }
  96658. var mesh = subMesh.getRenderingMesh();
  96659. var material = subMesh.getMaterial();
  96660. if (!material || !scene.activeCamera) {
  96661. return;
  96662. }
  96663. engine.enableEffect(this._effect);
  96664. // Logarithmic depth
  96665. if (material.useLogarithmicDepth) {
  96666. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  96667. }
  96668. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  96669. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  96670. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  96671. // Bones
  96672. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96673. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96674. }
  96675. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  96676. // Alpha test
  96677. if (material && material.needAlphaTesting()) {
  96678. var alphaTexture = material.getAlphaTestTexture();
  96679. if (alphaTexture) {
  96680. this._effect.setTexture("diffuseSampler", alphaTexture);
  96681. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  96682. }
  96683. }
  96684. engine.setZOffset(-this.zOffset);
  96685. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  96686. engine.setZOffset(0);
  96687. };
  96688. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  96689. var defines = [];
  96690. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  96691. var mesh = subMesh.getMesh();
  96692. var material = subMesh.getMaterial();
  96693. if (material) {
  96694. // Alpha test
  96695. if (material.needAlphaTesting()) {
  96696. defines.push("#define ALPHATEST");
  96697. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96698. attribs.push(BABYLON.VertexBuffer.UVKind);
  96699. defines.push("#define UV1");
  96700. }
  96701. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  96702. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96703. defines.push("#define UV2");
  96704. }
  96705. }
  96706. //Logarithmic depth
  96707. if (material.useLogarithmicDepth) {
  96708. defines.push("#define LOGARITHMICDEPTH");
  96709. }
  96710. }
  96711. // Bones
  96712. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96713. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96714. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96715. if (mesh.numBoneInfluencers > 4) {
  96716. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96717. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96718. }
  96719. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96720. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  96721. }
  96722. else {
  96723. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96724. }
  96725. // Instances
  96726. if (useInstances) {
  96727. defines.push("#define INSTANCES");
  96728. attribs.push("world0");
  96729. attribs.push("world1");
  96730. attribs.push("world2");
  96731. attribs.push("world3");
  96732. }
  96733. // Get correct effect
  96734. var join = defines.join("\n");
  96735. if (this._cachedDefines !== join) {
  96736. this._cachedDefines = join;
  96737. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  96738. }
  96739. return this._effect.isReady();
  96740. };
  96741. return OutlineRenderer;
  96742. }());
  96743. BABYLON.OutlineRenderer = OutlineRenderer;
  96744. })(BABYLON || (BABYLON = {}));
  96745. //# sourceMappingURL=babylon.outlineRenderer.js.map
  96746. var BABYLON;
  96747. (function (BABYLON) {
  96748. var FaceAdjacencies = /** @class */ (function () {
  96749. function FaceAdjacencies() {
  96750. this.edges = new Array();
  96751. this.edgesConnectedCount = 0;
  96752. }
  96753. return FaceAdjacencies;
  96754. }());
  96755. var EdgesRenderer = /** @class */ (function () {
  96756. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  96757. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  96758. if (epsilon === void 0) { epsilon = 0.95; }
  96759. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  96760. this.edgesWidthScalerForOrthographic = 1000.0;
  96761. this.edgesWidthScalerForPerspective = 50.0;
  96762. this._linesPositions = new Array();
  96763. this._linesNormals = new Array();
  96764. this._linesIndices = new Array();
  96765. this._buffers = {};
  96766. this._checkVerticesInsteadOfIndices = false;
  96767. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  96768. this.isEnabled = true;
  96769. this._source = source;
  96770. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  96771. this._epsilon = epsilon;
  96772. this._prepareRessources();
  96773. this._generateEdgesLines();
  96774. }
  96775. EdgesRenderer.prototype._prepareRessources = function () {
  96776. if (this._lineShader) {
  96777. return;
  96778. }
  96779. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  96780. attributes: ["position", "normal"],
  96781. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96782. });
  96783. this._lineShader.disableDepthWrite = true;
  96784. this._lineShader.backFaceCulling = false;
  96785. };
  96786. EdgesRenderer.prototype._rebuild = function () {
  96787. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96788. if (buffer) {
  96789. buffer._rebuild();
  96790. }
  96791. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96792. if (buffer) {
  96793. buffer._rebuild();
  96794. }
  96795. var scene = this._source.getScene();
  96796. var engine = scene.getEngine();
  96797. this._ib = engine.createIndexBuffer(this._linesIndices);
  96798. };
  96799. EdgesRenderer.prototype.dispose = function () {
  96800. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96801. if (buffer) {
  96802. buffer.dispose();
  96803. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96804. }
  96805. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96806. if (buffer) {
  96807. buffer.dispose();
  96808. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96809. }
  96810. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96811. this._lineShader.dispose();
  96812. };
  96813. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96814. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96815. return 0;
  96816. }
  96817. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96818. return 1;
  96819. }
  96820. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96821. return 2;
  96822. }
  96823. return -1;
  96824. };
  96825. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96826. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96827. return 0;
  96828. }
  96829. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96830. return 1;
  96831. }
  96832. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96833. return 2;
  96834. }
  96835. return -1;
  96836. };
  96837. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96838. var needToCreateLine;
  96839. if (edge === undefined) {
  96840. needToCreateLine = true;
  96841. }
  96842. else {
  96843. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96844. needToCreateLine = dotProduct < this._epsilon;
  96845. }
  96846. if (needToCreateLine) {
  96847. var offset = this._linesPositions.length / 3;
  96848. var normal = p0.subtract(p1);
  96849. normal.normalize();
  96850. // Positions
  96851. this._linesPositions.push(p0.x);
  96852. this._linesPositions.push(p0.y);
  96853. this._linesPositions.push(p0.z);
  96854. this._linesPositions.push(p0.x);
  96855. this._linesPositions.push(p0.y);
  96856. this._linesPositions.push(p0.z);
  96857. this._linesPositions.push(p1.x);
  96858. this._linesPositions.push(p1.y);
  96859. this._linesPositions.push(p1.z);
  96860. this._linesPositions.push(p1.x);
  96861. this._linesPositions.push(p1.y);
  96862. this._linesPositions.push(p1.z);
  96863. // Normals
  96864. this._linesNormals.push(p1.x);
  96865. this._linesNormals.push(p1.y);
  96866. this._linesNormals.push(p1.z);
  96867. this._linesNormals.push(-1);
  96868. this._linesNormals.push(p1.x);
  96869. this._linesNormals.push(p1.y);
  96870. this._linesNormals.push(p1.z);
  96871. this._linesNormals.push(1);
  96872. this._linesNormals.push(p0.x);
  96873. this._linesNormals.push(p0.y);
  96874. this._linesNormals.push(p0.z);
  96875. this._linesNormals.push(-1);
  96876. this._linesNormals.push(p0.x);
  96877. this._linesNormals.push(p0.y);
  96878. this._linesNormals.push(p0.z);
  96879. this._linesNormals.push(1);
  96880. // Indices
  96881. this._linesIndices.push(offset);
  96882. this._linesIndices.push(offset + 1);
  96883. this._linesIndices.push(offset + 2);
  96884. this._linesIndices.push(offset);
  96885. this._linesIndices.push(offset + 2);
  96886. this._linesIndices.push(offset + 3);
  96887. }
  96888. };
  96889. EdgesRenderer.prototype._generateEdgesLines = function () {
  96890. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96891. var indices = this._source.getIndices();
  96892. if (!indices || !positions) {
  96893. return;
  96894. }
  96895. // First let's find adjacencies
  96896. var adjacencies = new Array();
  96897. var faceNormals = new Array();
  96898. var index;
  96899. var faceAdjacencies;
  96900. // Prepare faces
  96901. for (index = 0; index < indices.length; index += 3) {
  96902. faceAdjacencies = new FaceAdjacencies();
  96903. var p0Index = indices[index];
  96904. var p1Index = indices[index + 1];
  96905. var p2Index = indices[index + 2];
  96906. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96907. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96908. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96909. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96910. faceNormal.normalize();
  96911. faceNormals.push(faceNormal);
  96912. adjacencies.push(faceAdjacencies);
  96913. }
  96914. // Scan
  96915. for (index = 0; index < adjacencies.length; index++) {
  96916. faceAdjacencies = adjacencies[index];
  96917. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96918. var otherFaceAdjacencies = adjacencies[otherIndex];
  96919. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96920. break;
  96921. }
  96922. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96923. continue;
  96924. }
  96925. var otherP0 = indices[otherIndex * 3];
  96926. var otherP1 = indices[otherIndex * 3 + 1];
  96927. var otherP2 = indices[otherIndex * 3 + 2];
  96928. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96929. var otherEdgeIndex = 0;
  96930. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96931. continue;
  96932. }
  96933. switch (edgeIndex) {
  96934. case 0:
  96935. if (this._checkVerticesInsteadOfIndices) {
  96936. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96937. }
  96938. else {
  96939. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96940. }
  96941. break;
  96942. case 1:
  96943. if (this._checkVerticesInsteadOfIndices) {
  96944. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96945. }
  96946. else {
  96947. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96948. }
  96949. break;
  96950. case 2:
  96951. if (this._checkVerticesInsteadOfIndices) {
  96952. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96953. }
  96954. else {
  96955. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96956. }
  96957. break;
  96958. }
  96959. if (otherEdgeIndex === -1) {
  96960. continue;
  96961. }
  96962. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96963. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96964. faceAdjacencies.edgesConnectedCount++;
  96965. otherFaceAdjacencies.edgesConnectedCount++;
  96966. if (faceAdjacencies.edgesConnectedCount === 3) {
  96967. break;
  96968. }
  96969. }
  96970. }
  96971. }
  96972. // Create lines
  96973. for (index = 0; index < adjacencies.length; index++) {
  96974. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  96975. var current = adjacencies[index];
  96976. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96977. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96978. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96979. }
  96980. // Merge into a single mesh
  96981. var engine = this._source.getScene().getEngine();
  96982. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96983. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96984. this._ib = engine.createIndexBuffer(this._linesIndices);
  96985. this._indicesCount = this._linesIndices.length;
  96986. };
  96987. EdgesRenderer.prototype.render = function () {
  96988. var scene = this._source.getScene();
  96989. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96990. return;
  96991. }
  96992. var engine = scene.getEngine();
  96993. this._lineShader._preBind();
  96994. // VBOs
  96995. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96996. scene.resetCachedMaterial();
  96997. this._lineShader.setColor4("color", this._source.edgesColor);
  96998. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96999. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  97000. }
  97001. else {
  97002. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  97003. }
  97004. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  97005. this._lineShader.bind(this._source.getWorldMatrix());
  97006. // Draw order
  97007. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  97008. this._lineShader.unbind();
  97009. engine.setDepthWrite(true);
  97010. };
  97011. return EdgesRenderer;
  97012. }());
  97013. BABYLON.EdgesRenderer = EdgesRenderer;
  97014. })(BABYLON || (BABYLON = {}));
  97015. //# sourceMappingURL=babylon.edgesRenderer.js.map
  97016. var BABYLON;
  97017. (function (BABYLON) {
  97018. // Adds the parser to the scene parsers.
  97019. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  97020. if (parsedData.effectLayers) {
  97021. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  97022. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  97023. container.effectLayers.push(effectLayer);
  97024. }
  97025. }
  97026. });
  97027. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  97028. var index = this.effectLayers.indexOf(toRemove);
  97029. if (index !== -1) {
  97030. this.effectLayers.splice(index, 1);
  97031. }
  97032. return index;
  97033. };
  97034. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  97035. this.effectLayers.push(newEffectLayer);
  97036. };
  97037. /**
  97038. * Defines the layer scene component responsible to manage any effect layers
  97039. * in a given scene.
  97040. */
  97041. var EffectLayerSceneComponent = /** @class */ (function () {
  97042. /**
  97043. * Creates a new instance of the component for the given scene
  97044. * @param scene Defines the scene to register the component in
  97045. */
  97046. function EffectLayerSceneComponent(scene) {
  97047. /**
  97048. * The component name helpfull to identify the component in the list of scene components.
  97049. */
  97050. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  97051. this._renderEffects = false;
  97052. this._needStencil = false;
  97053. this._previousStencilState = false;
  97054. this.scene = scene;
  97055. this._engine = scene.getEngine();
  97056. scene.effectLayers = new Array();
  97057. }
  97058. /**
  97059. * Registers the component in a given scene
  97060. */
  97061. EffectLayerSceneComponent.prototype.register = function () {
  97062. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  97063. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  97064. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  97065. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  97066. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  97067. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  97068. };
  97069. /**
  97070. * Rebuilds the elements related to this component in case of
  97071. * context lost for instance.
  97072. */
  97073. EffectLayerSceneComponent.prototype.rebuild = function () {
  97074. var layers = this.scene.effectLayers;
  97075. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  97076. var effectLayer = layers_1[_i];
  97077. effectLayer._rebuild();
  97078. }
  97079. };
  97080. /**
  97081. * Serializes the component data to the specified json object
  97082. * @param serializationObject The object to serialize to
  97083. */
  97084. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  97085. // Effect layers
  97086. serializationObject.effectLayers = [];
  97087. var layers = this.scene.effectLayers;
  97088. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  97089. var effectLayer = layers_2[_i];
  97090. if (effectLayer.serialize) {
  97091. serializationObject.effectLayers.push(effectLayer.serialize());
  97092. }
  97093. }
  97094. };
  97095. /**
  97096. * Adds all the element from the container to the scene
  97097. * @param container the container holding the elements
  97098. */
  97099. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  97100. var _this = this;
  97101. if (!container.effectLayers) {
  97102. return;
  97103. }
  97104. container.effectLayers.forEach(function (o) {
  97105. _this.scene.addEffectLayer(o);
  97106. });
  97107. };
  97108. /**
  97109. * Removes all the elements in the container from the scene
  97110. * @param container contains the elements to remove
  97111. */
  97112. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  97113. var _this = this;
  97114. if (!container.effectLayers) {
  97115. return;
  97116. }
  97117. container.effectLayers.forEach(function (o) {
  97118. _this.scene.removeEffectLayer(o);
  97119. });
  97120. };
  97121. /**
  97122. * Disposes the component and the associated ressources.
  97123. */
  97124. EffectLayerSceneComponent.prototype.dispose = function () {
  97125. var layers = this.scene.effectLayers;
  97126. while (layers.length) {
  97127. layers[0].dispose();
  97128. }
  97129. };
  97130. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  97131. var layers = this.scene.effectLayers;
  97132. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  97133. var layer = layers_3[_i];
  97134. if (!layer.hasMesh(mesh)) {
  97135. continue;
  97136. }
  97137. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  97138. var subMesh = _b[_a];
  97139. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  97140. return false;
  97141. }
  97142. }
  97143. }
  97144. return true;
  97145. };
  97146. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  97147. this._renderEffects = false;
  97148. this._needStencil = false;
  97149. var layers = this.scene.effectLayers;
  97150. if (layers && layers.length > 0) {
  97151. this._previousStencilState = this._engine.getStencilBuffer();
  97152. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  97153. var effectLayer = layers_4[_i];
  97154. if (effectLayer.shouldRender() &&
  97155. (!effectLayer.camera ||
  97156. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  97157. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  97158. this._renderEffects = true;
  97159. this._needStencil = this._needStencil || effectLayer.needStencil();
  97160. var renderTarget = effectLayer._mainTexture;
  97161. if (renderTarget._shouldRender()) {
  97162. this.scene.incrementRenderId();
  97163. renderTarget.render(false, false);
  97164. }
  97165. }
  97166. }
  97167. this.scene.incrementRenderId();
  97168. }
  97169. };
  97170. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  97171. // Activate effect Layer stencil
  97172. if (this._needStencil) {
  97173. this._engine.setStencilBuffer(true);
  97174. }
  97175. };
  97176. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  97177. // Restore effect Layer stencil
  97178. if (this._needStencil) {
  97179. this._engine.setStencilBuffer(this._previousStencilState);
  97180. }
  97181. };
  97182. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  97183. if (this._renderEffects) {
  97184. this._engine.setDepthBuffer(false);
  97185. var layers = this.scene.effectLayers;
  97186. for (var i = 0; i < layers.length; i++) {
  97187. var effectLayer = layers[i];
  97188. if (effectLayer.renderingGroupId === renderingGroupId) {
  97189. if (effectLayer.shouldRender()) {
  97190. effectLayer.render();
  97191. }
  97192. }
  97193. }
  97194. this._engine.setDepthBuffer(true);
  97195. }
  97196. };
  97197. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  97198. if (this._renderEffects) {
  97199. this._draw(-1);
  97200. }
  97201. };
  97202. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  97203. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  97204. this._draw(index);
  97205. }
  97206. };
  97207. return EffectLayerSceneComponent;
  97208. }());
  97209. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  97210. })(BABYLON || (BABYLON = {}));
  97211. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  97212. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97213. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97214. s = arguments[i];
  97215. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97216. t[p] = s[p];
  97217. }
  97218. return t;
  97219. };
  97220. var BABYLON;
  97221. (function (BABYLON) {
  97222. /**
  97223. * The effect layer Helps adding post process effect blended with the main pass.
  97224. *
  97225. * This can be for instance use to generate glow or higlight effects on the scene.
  97226. *
  97227. * The effect layer class can not be used directly and is intented to inherited from to be
  97228. * customized per effects.
  97229. */
  97230. var EffectLayer = /** @class */ (function () {
  97231. /**
  97232. * Instantiates a new effect Layer and references it in the scene.
  97233. * @param name The name of the layer
  97234. * @param scene The scene to use the layer in
  97235. */
  97236. function EffectLayer(
  97237. /** The Friendly of the effect in the scene */
  97238. name, scene) {
  97239. this._vertexBuffers = {};
  97240. this._maxSize = 0;
  97241. this._mainTextureDesiredSize = { width: 0, height: 0 };
  97242. this._shouldRender = true;
  97243. this._postProcesses = [];
  97244. this._textures = [];
  97245. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  97246. /**
  97247. * The clear color of the texture used to generate the glow map.
  97248. */
  97249. this.neutralColor = new BABYLON.Color4();
  97250. /**
  97251. * Specifies wether the highlight layer is enabled or not.
  97252. */
  97253. this.isEnabled = true;
  97254. /**
  97255. * An event triggered when the effect layer has been disposed.
  97256. */
  97257. this.onDisposeObservable = new BABYLON.Observable();
  97258. /**
  97259. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  97260. */
  97261. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  97262. /**
  97263. * An event triggered when the generated texture is being merged in the scene.
  97264. */
  97265. this.onBeforeComposeObservable = new BABYLON.Observable();
  97266. /**
  97267. * An event triggered when the generated texture has been merged in the scene.
  97268. */
  97269. this.onAfterComposeObservable = new BABYLON.Observable();
  97270. /**
  97271. * An event triggered when the efffect layer changes its size.
  97272. */
  97273. this.onSizeChangedObservable = new BABYLON.Observable();
  97274. this.name = name;
  97275. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97276. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  97277. if (!component) {
  97278. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  97279. this._scene._addComponent(component);
  97280. }
  97281. this._engine = this._scene.getEngine();
  97282. this._maxSize = this._engine.getCaps().maxTextureSize;
  97283. this._scene.effectLayers.push(this);
  97284. // Generate Buffers
  97285. this._generateIndexBuffer();
  97286. this._genrateVertexBuffer();
  97287. }
  97288. Object.defineProperty(EffectLayer.prototype, "camera", {
  97289. /**
  97290. * Gets the camera attached to the layer.
  97291. */
  97292. get: function () {
  97293. return this._effectLayerOptions.camera;
  97294. },
  97295. enumerable: true,
  97296. configurable: true
  97297. });
  97298. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  97299. /**
  97300. * Gets the rendering group id the layer should render in.
  97301. */
  97302. get: function () {
  97303. return this._effectLayerOptions.renderingGroupId;
  97304. },
  97305. enumerable: true,
  97306. configurable: true
  97307. });
  97308. /**
  97309. * Initializes the effect layer with the required options.
  97310. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  97311. */
  97312. EffectLayer.prototype._init = function (options) {
  97313. // Adapt options
  97314. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97315. this._setMainTextureSize();
  97316. this._createMainTexture();
  97317. this._createTextureAndPostProcesses();
  97318. this._mergeEffect = this._createMergeEffect();
  97319. };
  97320. /**
  97321. * Generates the index buffer of the full screen quad blending to the main canvas.
  97322. */
  97323. EffectLayer.prototype._generateIndexBuffer = function () {
  97324. // Indices
  97325. var indices = [];
  97326. indices.push(0);
  97327. indices.push(1);
  97328. indices.push(2);
  97329. indices.push(0);
  97330. indices.push(2);
  97331. indices.push(3);
  97332. this._indexBuffer = this._engine.createIndexBuffer(indices);
  97333. };
  97334. /**
  97335. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  97336. */
  97337. EffectLayer.prototype._genrateVertexBuffer = function () {
  97338. // VBO
  97339. var vertices = [];
  97340. vertices.push(1, 1);
  97341. vertices.push(-1, 1);
  97342. vertices.push(-1, -1);
  97343. vertices.push(1, -1);
  97344. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97345. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97346. };
  97347. /**
  97348. * Sets the main texture desired size which is the closest power of two
  97349. * of the engine canvas size.
  97350. */
  97351. EffectLayer.prototype._setMainTextureSize = function () {
  97352. if (this._effectLayerOptions.mainTextureFixedSize) {
  97353. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  97354. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  97355. }
  97356. else {
  97357. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  97358. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  97359. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  97360. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  97361. }
  97362. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  97363. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  97364. };
  97365. /**
  97366. * Creates the main texture for the effect layer.
  97367. */
  97368. EffectLayer.prototype._createMainTexture = function () {
  97369. var _this = this;
  97370. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  97371. width: this._mainTextureDesiredSize.width,
  97372. height: this._mainTextureDesiredSize.height
  97373. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97374. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  97375. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97376. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97377. this._mainTexture.anisotropicFilteringLevel = 1;
  97378. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97379. this._mainTexture.renderParticles = false;
  97380. this._mainTexture.renderList = null;
  97381. this._mainTexture.ignoreCameraViewport = true;
  97382. // Custom render function
  97383. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  97384. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  97385. var index;
  97386. var engine = _this._scene.getEngine();
  97387. if (depthOnlySubMeshes.length) {
  97388. engine.setColorWrite(false);
  97389. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  97390. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  97391. }
  97392. engine.setColorWrite(true);
  97393. }
  97394. for (index = 0; index < opaqueSubMeshes.length; index++) {
  97395. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  97396. }
  97397. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  97398. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  97399. }
  97400. for (index = 0; index < transparentSubMeshes.length; index++) {
  97401. _this._renderSubMesh(transparentSubMeshes.data[index]);
  97402. }
  97403. };
  97404. this._mainTexture.onClearObservable.add(function (engine) {
  97405. engine.clear(_this.neutralColor, true, true, true);
  97406. });
  97407. };
  97408. /**
  97409. * Checks for the readiness of the element composing the layer.
  97410. * @param subMesh the mesh to check for
  97411. * @param useInstances specify wether or not to use instances to render the mesh
  97412. * @param emissiveTexture the associated emissive texture used to generate the glow
  97413. * @return true if ready otherwise, false
  97414. */
  97415. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  97416. var material = subMesh.getMaterial();
  97417. if (!material) {
  97418. return false;
  97419. }
  97420. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  97421. return false;
  97422. }
  97423. var defines = [];
  97424. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97425. var mesh = subMesh.getMesh();
  97426. var uv1 = false;
  97427. var uv2 = false;
  97428. // Alpha test
  97429. if (material && material.needAlphaTesting()) {
  97430. var alphaTexture = material.getAlphaTestTexture();
  97431. if (alphaTexture) {
  97432. defines.push("#define ALPHATEST");
  97433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97434. alphaTexture.coordinatesIndex === 1) {
  97435. defines.push("#define DIFFUSEUV2");
  97436. uv2 = true;
  97437. }
  97438. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97439. defines.push("#define DIFFUSEUV1");
  97440. uv1 = true;
  97441. }
  97442. }
  97443. }
  97444. // Emissive
  97445. if (emissiveTexture) {
  97446. defines.push("#define EMISSIVE");
  97447. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97448. emissiveTexture.coordinatesIndex === 1) {
  97449. defines.push("#define EMISSIVEUV2");
  97450. uv2 = true;
  97451. }
  97452. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97453. defines.push("#define EMISSIVEUV1");
  97454. uv1 = true;
  97455. }
  97456. }
  97457. if (uv1) {
  97458. attribs.push(BABYLON.VertexBuffer.UVKind);
  97459. defines.push("#define UV1");
  97460. }
  97461. if (uv2) {
  97462. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97463. defines.push("#define UV2");
  97464. }
  97465. // Bones
  97466. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  97467. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  97468. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  97469. if (mesh.numBoneInfluencers > 4) {
  97470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  97471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  97472. }
  97473. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  97474. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  97475. }
  97476. else {
  97477. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97478. }
  97479. // Morph targets
  97480. var manager = mesh.morphTargetManager;
  97481. var morphInfluencers = 0;
  97482. if (manager) {
  97483. if (manager.numInfluencers > 0) {
  97484. defines.push("#define MORPHTARGETS");
  97485. morphInfluencers = manager.numInfluencers;
  97486. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  97487. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  97488. }
  97489. }
  97490. // Instances
  97491. if (useInstances) {
  97492. defines.push("#define INSTANCES");
  97493. attribs.push("world0");
  97494. attribs.push("world1");
  97495. attribs.push("world2");
  97496. attribs.push("world3");
  97497. }
  97498. // Get correct effect
  97499. var join = defines.join("\n");
  97500. if (this._cachedDefines !== join) {
  97501. this._cachedDefines = join;
  97502. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  97503. }
  97504. return this._effectLayerMapGenerationEffect.isReady();
  97505. };
  97506. /**
  97507. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  97508. */
  97509. EffectLayer.prototype.render = function () {
  97510. var currentEffect = this._mergeEffect;
  97511. // Check
  97512. if (!currentEffect.isReady())
  97513. return;
  97514. for (var i = 0; i < this._postProcesses.length; i++) {
  97515. if (!this._postProcesses[i].isReady()) {
  97516. return;
  97517. }
  97518. }
  97519. var engine = this._scene.getEngine();
  97520. this.onBeforeComposeObservable.notifyObservers(this);
  97521. // Render
  97522. engine.enableEffect(currentEffect);
  97523. engine.setState(false);
  97524. // VBOs
  97525. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97526. // Cache
  97527. var previousAlphaMode = engine.getAlphaMode();
  97528. // Go Blend.
  97529. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  97530. // Blends the map on the main canvas.
  97531. this._internalRender(currentEffect);
  97532. // Restore Alpha
  97533. engine.setAlphaMode(previousAlphaMode);
  97534. this.onAfterComposeObservable.notifyObservers(this);
  97535. // Handle size changes.
  97536. var size = this._mainTexture.getSize();
  97537. this._setMainTextureSize();
  97538. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  97539. // Recreate RTT and post processes on size change.
  97540. this.onSizeChangedObservable.notifyObservers(this);
  97541. this._disposeTextureAndPostProcesses();
  97542. this._createMainTexture();
  97543. this._createTextureAndPostProcesses();
  97544. }
  97545. };
  97546. /**
  97547. * Determine if a given mesh will be used in the current effect.
  97548. * @param mesh mesh to test
  97549. * @returns true if the mesh will be used
  97550. */
  97551. EffectLayer.prototype.hasMesh = function (mesh) {
  97552. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  97553. return true;
  97554. }
  97555. return false;
  97556. };
  97557. /**
  97558. * Returns true if the layer contains information to display, otherwise false.
  97559. * @returns true if the glow layer should be rendered
  97560. */
  97561. EffectLayer.prototype.shouldRender = function () {
  97562. return this.isEnabled && this._shouldRender;
  97563. };
  97564. /**
  97565. * Returns true if the mesh should render, otherwise false.
  97566. * @param mesh The mesh to render
  97567. * @returns true if it should render otherwise false
  97568. */
  97569. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  97570. return true;
  97571. };
  97572. /**
  97573. * Returns true if the mesh should render, otherwise false.
  97574. * @param mesh The mesh to render
  97575. * @returns true if it should render otherwise false
  97576. */
  97577. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  97578. return true;
  97579. };
  97580. /**
  97581. * Renders the submesh passed in parameter to the generation map.
  97582. */
  97583. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  97584. var _this = this;
  97585. if (!this.shouldRender()) {
  97586. return;
  97587. }
  97588. var material = subMesh.getMaterial();
  97589. var mesh = subMesh.getRenderingMesh();
  97590. var scene = this._scene;
  97591. var engine = scene.getEngine();
  97592. if (!material) {
  97593. return;
  97594. }
  97595. // Do not block in blend mode.
  97596. if (material.needAlphaBlendingForMesh(mesh)) {
  97597. return;
  97598. }
  97599. // Culling
  97600. engine.setState(material.backFaceCulling);
  97601. // Managing instances
  97602. var batch = mesh._getInstancesRenderList(subMesh._id);
  97603. if (batch.mustReturn) {
  97604. return;
  97605. }
  97606. // Early Exit per mesh
  97607. if (!this._shouldRenderMesh(mesh)) {
  97608. return;
  97609. }
  97610. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97611. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  97612. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  97613. engine.enableEffect(this._effectLayerMapGenerationEffect);
  97614. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  97615. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  97616. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  97617. // Alpha test
  97618. if (material && material.needAlphaTesting()) {
  97619. var alphaTexture = material.getAlphaTestTexture();
  97620. if (alphaTexture) {
  97621. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  97622. var textureMatrix = alphaTexture.getTextureMatrix();
  97623. if (textureMatrix) {
  97624. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  97625. }
  97626. }
  97627. }
  97628. // Glow emissive only
  97629. if (this._emissiveTextureAndColor.texture) {
  97630. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  97631. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  97632. }
  97633. // Bones
  97634. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97635. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97636. }
  97637. // Morph targets
  97638. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  97639. // Draw
  97640. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  97641. }
  97642. else {
  97643. // Need to reset refresh rate of the main map
  97644. this._mainTexture.resetRefreshCounter();
  97645. }
  97646. };
  97647. /**
  97648. * Rebuild the required buffers.
  97649. * @hidden Internal use only.
  97650. */
  97651. EffectLayer.prototype._rebuild = function () {
  97652. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97653. if (vb) {
  97654. vb._rebuild();
  97655. }
  97656. this._generateIndexBuffer();
  97657. };
  97658. /**
  97659. * Dispose only the render target textures and post process.
  97660. */
  97661. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  97662. this._mainTexture.dispose();
  97663. for (var i = 0; i < this._postProcesses.length; i++) {
  97664. if (this._postProcesses[i]) {
  97665. this._postProcesses[i].dispose();
  97666. }
  97667. }
  97668. this._postProcesses = [];
  97669. for (var i = 0; i < this._textures.length; i++) {
  97670. if (this._textures[i]) {
  97671. this._textures[i].dispose();
  97672. }
  97673. }
  97674. this._textures = [];
  97675. };
  97676. /**
  97677. * Dispose the highlight layer and free resources.
  97678. */
  97679. EffectLayer.prototype.dispose = function () {
  97680. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97681. if (vertexBuffer) {
  97682. vertexBuffer.dispose();
  97683. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97684. }
  97685. if (this._indexBuffer) {
  97686. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97687. this._indexBuffer = null;
  97688. }
  97689. // Clean textures and post processes
  97690. this._disposeTextureAndPostProcesses();
  97691. // Remove from scene
  97692. var index = this._scene.effectLayers.indexOf(this, 0);
  97693. if (index > -1) {
  97694. this._scene.effectLayers.splice(index, 1);
  97695. }
  97696. // Callback
  97697. this.onDisposeObservable.notifyObservers(this);
  97698. this.onDisposeObservable.clear();
  97699. this.onBeforeRenderMainTextureObservable.clear();
  97700. this.onBeforeComposeObservable.clear();
  97701. this.onAfterComposeObservable.clear();
  97702. this.onSizeChangedObservable.clear();
  97703. };
  97704. /**
  97705. * Gets the class name of the effect layer
  97706. * @returns the string with the class name of the effect layer
  97707. */
  97708. EffectLayer.prototype.getClassName = function () {
  97709. return "EffectLayer";
  97710. };
  97711. /**
  97712. * Creates an effect layer from parsed effect layer data
  97713. * @param parsedEffectLayer defines effect layer data
  97714. * @param scene defines the current scene
  97715. * @param rootUrl defines the root URL containing the effect layer information
  97716. * @returns a parsed effect Layer
  97717. */
  97718. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  97719. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  97720. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  97721. };
  97722. __decorate([
  97723. BABYLON.serialize()
  97724. ], EffectLayer.prototype, "name", void 0);
  97725. __decorate([
  97726. BABYLON.serializeAsColor4()
  97727. ], EffectLayer.prototype, "neutralColor", void 0);
  97728. __decorate([
  97729. BABYLON.serialize()
  97730. ], EffectLayer.prototype, "isEnabled", void 0);
  97731. __decorate([
  97732. BABYLON.serializeAsCameraReference()
  97733. ], EffectLayer.prototype, "camera", null);
  97734. __decorate([
  97735. BABYLON.serialize()
  97736. ], EffectLayer.prototype, "renderingGroupId", null);
  97737. return EffectLayer;
  97738. }());
  97739. BABYLON.EffectLayer = EffectLayer;
  97740. })(BABYLON || (BABYLON = {}));
  97741. //# sourceMappingURL=babylon.effectLayer.js.map
  97742. var BABYLON;
  97743. (function (BABYLON) {
  97744. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  97745. for (var index = 0; index < this.effectLayers.length; index++) {
  97746. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  97747. return this.effectLayers[index];
  97748. }
  97749. }
  97750. return null;
  97751. };
  97752. /**
  97753. * Special Glow Blur post process only blurring the alpha channel
  97754. * It enforces keeping the most luminous color in the color channel.
  97755. */
  97756. var GlowBlurPostProcess = /** @class */ (function (_super) {
  97757. __extends(GlowBlurPostProcess, _super);
  97758. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  97759. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  97760. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  97761. _this.direction = direction;
  97762. _this.kernel = kernel;
  97763. _this.onApplyObservable.add(function (effect) {
  97764. effect.setFloat2("screenSize", _this.width, _this.height);
  97765. effect.setVector2("direction", _this.direction);
  97766. effect.setFloat("blurWidth", _this.kernel);
  97767. });
  97768. return _this;
  97769. }
  97770. return GlowBlurPostProcess;
  97771. }(BABYLON.PostProcess));
  97772. /**
  97773. * The highlight layer Helps adding a glow effect around a mesh.
  97774. *
  97775. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97776. * glowy meshes to your scene.
  97777. *
  97778. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  97779. */
  97780. var HighlightLayer = /** @class */ (function (_super) {
  97781. __extends(HighlightLayer, _super);
  97782. /**
  97783. * Instantiates a new highlight Layer and references it to the scene..
  97784. * @param name The name of the layer
  97785. * @param scene The scene to use the layer in
  97786. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97787. */
  97788. function HighlightLayer(name, scene, options) {
  97789. var _this = _super.call(this, name, scene) || this;
  97790. _this.name = name;
  97791. /**
  97792. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97793. */
  97794. _this.innerGlow = true;
  97795. /**
  97796. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97797. */
  97798. _this.outerGlow = true;
  97799. /**
  97800. * An event triggered when the highlight layer is being blurred.
  97801. */
  97802. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97803. /**
  97804. * An event triggered when the highlight layer has been blurred.
  97805. */
  97806. _this.onAfterBlurObservable = new BABYLON.Observable();
  97807. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97808. _this._meshes = {};
  97809. _this._excludedMeshes = {};
  97810. _this.neutralColor = HighlightLayer.NeutralColor;
  97811. // Warn on stencil
  97812. if (!_this._engine.isStencilEnable) {
  97813. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  97814. }
  97815. // Adapt options
  97816. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97817. // Initialize the layer
  97818. _this._init({
  97819. alphaBlendingMode: _this._options.alphaBlendingMode,
  97820. camera: _this._options.camera,
  97821. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97822. mainTextureRatio: _this._options.mainTextureRatio,
  97823. renderingGroupId: _this._options.renderingGroupId
  97824. });
  97825. // Do not render as long as no meshes have been added
  97826. _this._shouldRender = false;
  97827. return _this;
  97828. }
  97829. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97830. /**
  97831. * Gets the horizontal size of the blur.
  97832. */
  97833. get: function () {
  97834. return this._horizontalBlurPostprocess.kernel;
  97835. },
  97836. /**
  97837. * Specifies the horizontal size of the blur.
  97838. */
  97839. set: function (value) {
  97840. this._horizontalBlurPostprocess.kernel = value;
  97841. },
  97842. enumerable: true,
  97843. configurable: true
  97844. });
  97845. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97846. /**
  97847. * Gets the vertical size of the blur.
  97848. */
  97849. get: function () {
  97850. return this._verticalBlurPostprocess.kernel;
  97851. },
  97852. /**
  97853. * Specifies the vertical size of the blur.
  97854. */
  97855. set: function (value) {
  97856. this._verticalBlurPostprocess.kernel = value;
  97857. },
  97858. enumerable: true,
  97859. configurable: true
  97860. });
  97861. /**
  97862. * Get the effect name of the layer.
  97863. * @return The effect name
  97864. */
  97865. HighlightLayer.prototype.getEffectName = function () {
  97866. return HighlightLayer.EffectName;
  97867. };
  97868. /**
  97869. * Create the merge effect. This is the shader use to blit the information back
  97870. * to the main canvas at the end of the scene rendering.
  97871. */
  97872. HighlightLayer.prototype._createMergeEffect = function () {
  97873. // Effect
  97874. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97875. };
  97876. /**
  97877. * Creates the render target textures and post processes used in the highlight layer.
  97878. */
  97879. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97880. var _this = this;
  97881. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97882. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97883. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97884. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97885. var textureType = 0;
  97886. if (this._engine.getCaps().textureHalfFloatRender) {
  97887. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97888. }
  97889. else {
  97890. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97891. }
  97892. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97893. width: blurTextureWidth,
  97894. height: blurTextureHeight
  97895. }, this._scene, false, true, textureType);
  97896. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97897. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97898. this._blurTexture.anisotropicFilteringLevel = 16;
  97899. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97900. this._blurTexture.renderParticles = false;
  97901. this._blurTexture.ignoreCameraViewport = true;
  97902. this._textures = [this._blurTexture];
  97903. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97904. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97905. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97906. effect.setTexture("textureSampler", _this._mainTexture);
  97907. });
  97908. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97909. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97910. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97911. });
  97912. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97913. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97914. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97915. });
  97916. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97917. }
  97918. else {
  97919. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97920. width: blurTextureWidth,
  97921. height: blurTextureHeight
  97922. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97923. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97924. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97925. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97926. effect.setTexture("textureSampler", _this._mainTexture);
  97927. });
  97928. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97929. width: blurTextureWidth,
  97930. height: blurTextureHeight
  97931. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97932. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97933. }
  97934. this._mainTexture.onAfterUnbindObservable.add(function () {
  97935. _this.onBeforeBlurObservable.notifyObservers(_this);
  97936. var internalTexture = _this._blurTexture.getInternalTexture();
  97937. if (internalTexture) {
  97938. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97939. }
  97940. _this.onAfterBlurObservable.notifyObservers(_this);
  97941. });
  97942. // Prevent autoClear.
  97943. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97944. };
  97945. /**
  97946. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97947. */
  97948. HighlightLayer.prototype.needStencil = function () {
  97949. return true;
  97950. };
  97951. /**
  97952. * Checks for the readiness of the element composing the layer.
  97953. * @param subMesh the mesh to check for
  97954. * @param useInstances specify wether or not to use instances to render the mesh
  97955. * @param emissiveTexture the associated emissive texture used to generate the glow
  97956. * @return true if ready otherwise, false
  97957. */
  97958. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97959. var material = subMesh.getMaterial();
  97960. var mesh = subMesh.getRenderingMesh();
  97961. if (!material || !mesh || !this._meshes) {
  97962. return false;
  97963. }
  97964. var emissiveTexture = null;
  97965. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97966. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97967. emissiveTexture = material.emissiveTexture;
  97968. }
  97969. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97970. };
  97971. /**
  97972. * Implementation specific of rendering the generating effect on the main canvas.
  97973. * @param effect The effect used to render through
  97974. */
  97975. HighlightLayer.prototype._internalRender = function (effect) {
  97976. // Texture
  97977. effect.setTexture("textureSampler", this._blurTexture);
  97978. // Cache
  97979. var engine = this._engine;
  97980. var previousStencilBuffer = engine.getStencilBuffer();
  97981. var previousStencilFunction = engine.getStencilFunction();
  97982. var previousStencilMask = engine.getStencilMask();
  97983. var previousStencilOperationPass = engine.getStencilOperationPass();
  97984. var previousStencilOperationFail = engine.getStencilOperationFail();
  97985. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97986. var previousStencilReference = engine.getStencilFunctionReference();
  97987. // Stencil operations
  97988. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97989. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97990. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97991. // Draw order
  97992. engine.setStencilMask(0x00);
  97993. engine.setStencilBuffer(true);
  97994. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97995. // 2 passes inner outer
  97996. if (this.outerGlow) {
  97997. effect.setFloat("offset", 0);
  97998. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97999. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98000. }
  98001. if (this.innerGlow) {
  98002. effect.setFloat("offset", 1);
  98003. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  98004. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98005. }
  98006. // Restore Cache
  98007. engine.setStencilFunction(previousStencilFunction);
  98008. engine.setStencilMask(previousStencilMask);
  98009. engine.setStencilBuffer(previousStencilBuffer);
  98010. engine.setStencilOperationPass(previousStencilOperationPass);
  98011. engine.setStencilOperationFail(previousStencilOperationFail);
  98012. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  98013. engine.setStencilFunctionReference(previousStencilReference);
  98014. };
  98015. /**
  98016. * Returns true if the layer contains information to display, otherwise false.
  98017. */
  98018. HighlightLayer.prototype.shouldRender = function () {
  98019. if (_super.prototype.shouldRender.call(this)) {
  98020. return this._meshes ? true : false;
  98021. }
  98022. return false;
  98023. };
  98024. /**
  98025. * Returns true if the mesh should render, otherwise false.
  98026. * @param mesh The mesh to render
  98027. * @returns true if it should render otherwise false
  98028. */
  98029. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  98030. // Excluded Mesh
  98031. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  98032. return false;
  98033. }
  98034. ;
  98035. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98036. return false;
  98037. }
  98038. return true;
  98039. };
  98040. /**
  98041. * Sets the required values for both the emissive texture and and the main color.
  98042. */
  98043. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98044. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98045. if (highlightLayerMesh) {
  98046. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  98047. }
  98048. else {
  98049. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98050. }
  98051. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98052. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98053. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  98054. }
  98055. else {
  98056. this._emissiveTextureAndColor.texture = null;
  98057. }
  98058. };
  98059. /**
  98060. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  98061. * @param mesh The mesh to exclude from the highlight layer
  98062. */
  98063. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  98064. if (!this._excludedMeshes) {
  98065. return;
  98066. }
  98067. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98068. if (!meshExcluded) {
  98069. this._excludedMeshes[mesh.uniqueId] = {
  98070. mesh: mesh,
  98071. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  98072. mesh.getEngine().setStencilBuffer(false);
  98073. }),
  98074. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  98075. mesh.getEngine().setStencilBuffer(true);
  98076. }),
  98077. };
  98078. }
  98079. };
  98080. /**
  98081. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  98082. * @param mesh The mesh to highlight
  98083. */
  98084. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  98085. if (!this._excludedMeshes) {
  98086. return;
  98087. }
  98088. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98089. if (meshExcluded) {
  98090. if (meshExcluded.beforeRender) {
  98091. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  98092. }
  98093. if (meshExcluded.afterRender) {
  98094. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  98095. }
  98096. }
  98097. this._excludedMeshes[mesh.uniqueId] = null;
  98098. };
  98099. /**
  98100. * Determine if a given mesh will be highlighted by the current HighlightLayer
  98101. * @param mesh mesh to test
  98102. * @returns true if the mesh will be highlighted by the current HighlightLayer
  98103. */
  98104. HighlightLayer.prototype.hasMesh = function (mesh) {
  98105. if (!this._meshes) {
  98106. return false;
  98107. }
  98108. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98109. return false;
  98110. }
  98111. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  98112. };
  98113. /**
  98114. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  98115. * @param mesh The mesh to highlight
  98116. * @param color The color of the highlight
  98117. * @param glowEmissiveOnly Extract the glow from the emissive texture
  98118. */
  98119. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  98120. var _this = this;
  98121. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  98122. if (!this._meshes) {
  98123. return;
  98124. }
  98125. var meshHighlight = this._meshes[mesh.uniqueId];
  98126. if (meshHighlight) {
  98127. meshHighlight.color = color;
  98128. }
  98129. else {
  98130. this._meshes[mesh.uniqueId] = {
  98131. mesh: mesh,
  98132. color: color,
  98133. // Lambda required for capture due to Observable this context
  98134. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  98135. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  98136. _this._defaultStencilReference(mesh);
  98137. }
  98138. else {
  98139. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  98140. }
  98141. }),
  98142. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  98143. glowEmissiveOnly: glowEmissiveOnly
  98144. };
  98145. mesh.onDisposeObservable.add(function () {
  98146. _this._disposeMesh(mesh);
  98147. });
  98148. }
  98149. this._shouldRender = true;
  98150. };
  98151. /**
  98152. * Remove a mesh from the highlight layer in order to make it stop glowing.
  98153. * @param mesh The mesh to highlight
  98154. */
  98155. HighlightLayer.prototype.removeMesh = function (mesh) {
  98156. if (!this._meshes) {
  98157. return;
  98158. }
  98159. var meshHighlight = this._meshes[mesh.uniqueId];
  98160. if (meshHighlight) {
  98161. if (meshHighlight.observerHighlight) {
  98162. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98163. }
  98164. if (meshHighlight.observerDefault) {
  98165. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98166. }
  98167. delete this._meshes[mesh.uniqueId];
  98168. }
  98169. this._shouldRender = false;
  98170. for (var meshHighlightToCheck in this._meshes) {
  98171. if (this._meshes[meshHighlightToCheck]) {
  98172. this._shouldRender = true;
  98173. break;
  98174. }
  98175. }
  98176. };
  98177. /**
  98178. * Force the stencil to the normal expected value for none glowing parts
  98179. */
  98180. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  98181. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  98182. };
  98183. /**
  98184. * Free any resources and references associated to a mesh.
  98185. * Internal use
  98186. * @param mesh The mesh to free.
  98187. */
  98188. HighlightLayer.prototype._disposeMesh = function (mesh) {
  98189. this.removeMesh(mesh);
  98190. this.removeExcludedMesh(mesh);
  98191. };
  98192. /**
  98193. * Dispose the highlight layer and free resources.
  98194. */
  98195. HighlightLayer.prototype.dispose = function () {
  98196. if (this._meshes) {
  98197. // Clean mesh references
  98198. for (var id in this._meshes) {
  98199. var meshHighlight = this._meshes[id];
  98200. if (meshHighlight && meshHighlight.mesh) {
  98201. if (meshHighlight.observerHighlight) {
  98202. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98203. }
  98204. if (meshHighlight.observerDefault) {
  98205. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98206. }
  98207. }
  98208. }
  98209. this._meshes = null;
  98210. }
  98211. if (this._excludedMeshes) {
  98212. for (var id in this._excludedMeshes) {
  98213. var meshHighlight = this._excludedMeshes[id];
  98214. if (meshHighlight) {
  98215. if (meshHighlight.beforeRender) {
  98216. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  98217. }
  98218. if (meshHighlight.afterRender) {
  98219. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  98220. }
  98221. }
  98222. }
  98223. this._excludedMeshes = null;
  98224. }
  98225. _super.prototype.dispose.call(this);
  98226. };
  98227. /**
  98228. * Gets the class name of the effect layer
  98229. * @returns the string with the class name of the effect layer
  98230. */
  98231. HighlightLayer.prototype.getClassName = function () {
  98232. return "HighlightLayer";
  98233. };
  98234. /**
  98235. * Serializes this Highlight layer
  98236. * @returns a serialized Highlight layer object
  98237. */
  98238. HighlightLayer.prototype.serialize = function () {
  98239. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98240. serializationObject.customType = "BABYLON.HighlightLayer";
  98241. // Highlighted meshes
  98242. serializationObject.meshes = [];
  98243. if (this._meshes) {
  98244. for (var m in this._meshes) {
  98245. var mesh = this._meshes[m];
  98246. if (mesh) {
  98247. serializationObject.meshes.push({
  98248. glowEmissiveOnly: mesh.glowEmissiveOnly,
  98249. color: mesh.color.asArray(),
  98250. meshId: mesh.mesh.id
  98251. });
  98252. }
  98253. }
  98254. }
  98255. // Excluded meshes
  98256. serializationObject.excludedMeshes = [];
  98257. if (this._excludedMeshes) {
  98258. for (var e in this._excludedMeshes) {
  98259. var excludedMesh = this._excludedMeshes[e];
  98260. if (excludedMesh) {
  98261. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  98262. }
  98263. }
  98264. }
  98265. return serializationObject;
  98266. };
  98267. /**
  98268. * Creates a Highlight layer from parsed Highlight layer data
  98269. * @param parsedHightlightLayer defines the Highlight layer data
  98270. * @param scene defines the current scene
  98271. * @param rootUrl defines the root URL containing the Highlight layer information
  98272. * @returns a parsed Highlight layer
  98273. */
  98274. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  98275. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  98276. var index;
  98277. // Excluded meshes
  98278. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  98279. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  98280. if (mesh) {
  98281. hl.addExcludedMesh(mesh);
  98282. }
  98283. }
  98284. // Included meshes
  98285. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  98286. var highlightedMesh = parsedHightlightLayer.meshes[index];
  98287. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  98288. if (mesh) {
  98289. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  98290. }
  98291. }
  98292. return hl;
  98293. };
  98294. /**
  98295. * Effect Name of the highlight layer.
  98296. */
  98297. HighlightLayer.EffectName = "HighlightLayer";
  98298. /**
  98299. * The neutral color used during the preparation of the glow effect.
  98300. * This is black by default as the blend operation is a blend operation.
  98301. */
  98302. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  98303. /**
  98304. * Stencil value used for glowing meshes.
  98305. */
  98306. HighlightLayer.GlowingMeshStencilReference = 0x02;
  98307. /**
  98308. * Stencil value used for the other meshes in the scene.
  98309. */
  98310. HighlightLayer.NormalMeshStencilReference = 0x01;
  98311. __decorate([
  98312. BABYLON.serialize()
  98313. ], HighlightLayer.prototype, "innerGlow", void 0);
  98314. __decorate([
  98315. BABYLON.serialize()
  98316. ], HighlightLayer.prototype, "outerGlow", void 0);
  98317. __decorate([
  98318. BABYLON.serialize()
  98319. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  98320. __decorate([
  98321. BABYLON.serialize()
  98322. ], HighlightLayer.prototype, "blurVerticalSize", null);
  98323. __decorate([
  98324. BABYLON.serialize("options")
  98325. ], HighlightLayer.prototype, "_options", void 0);
  98326. return HighlightLayer;
  98327. }(BABYLON.EffectLayer));
  98328. BABYLON.HighlightLayer = HighlightLayer;
  98329. })(BABYLON || (BABYLON = {}));
  98330. //# sourceMappingURL=babylon.highlightLayer.js.map
  98331. var BABYLON;
  98332. (function (BABYLON) {
  98333. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  98334. for (var index = 0; index < this.effectLayers.length; index++) {
  98335. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  98336. return this.effectLayers[index];
  98337. }
  98338. }
  98339. return null;
  98340. };
  98341. /**
  98342. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  98343. *
  98344. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98345. * glowy meshes to your scene.
  98346. *
  98347. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  98348. */
  98349. var GlowLayer = /** @class */ (function (_super) {
  98350. __extends(GlowLayer, _super);
  98351. /**
  98352. * Instantiates a new glow Layer and references it to the scene.
  98353. * @param name The name of the layer
  98354. * @param scene The scene to use the layer in
  98355. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  98356. */
  98357. function GlowLayer(name, scene, options) {
  98358. var _this = _super.call(this, name, scene) || this;
  98359. _this._intensity = 1.0;
  98360. _this._includedOnlyMeshes = [];
  98361. _this._excludedMeshes = [];
  98362. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  98363. // Adapt options
  98364. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  98365. // Initialize the layer
  98366. _this._init({
  98367. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  98368. camera: _this._options.camera,
  98369. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  98370. mainTextureRatio: _this._options.mainTextureRatio,
  98371. renderingGroupId: _this._options.renderingGroupId
  98372. });
  98373. return _this;
  98374. }
  98375. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  98376. /**
  98377. * Gets the kernel size of the blur.
  98378. */
  98379. get: function () {
  98380. return this._horizontalBlurPostprocess1.kernel;
  98381. },
  98382. /**
  98383. * Sets the kernel size of the blur.
  98384. */
  98385. set: function (value) {
  98386. this._horizontalBlurPostprocess1.kernel = value;
  98387. this._verticalBlurPostprocess1.kernel = value;
  98388. this._horizontalBlurPostprocess2.kernel = value;
  98389. this._verticalBlurPostprocess2.kernel = value;
  98390. },
  98391. enumerable: true,
  98392. configurable: true
  98393. });
  98394. Object.defineProperty(GlowLayer.prototype, "intensity", {
  98395. /**
  98396. * Gets the glow intensity.
  98397. */
  98398. get: function () {
  98399. return this._intensity;
  98400. },
  98401. /**
  98402. * Sets the glow intensity.
  98403. */
  98404. set: function (value) {
  98405. this._intensity = value;
  98406. },
  98407. enumerable: true,
  98408. configurable: true
  98409. });
  98410. /**
  98411. * Get the effect name of the layer.
  98412. * @return The effect name
  98413. */
  98414. GlowLayer.prototype.getEffectName = function () {
  98415. return GlowLayer.EffectName;
  98416. };
  98417. /**
  98418. * Create the merge effect. This is the shader use to blit the information back
  98419. * to the main canvas at the end of the scene rendering.
  98420. */
  98421. GlowLayer.prototype._createMergeEffect = function () {
  98422. // Effect
  98423. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  98424. };
  98425. /**
  98426. * Creates the render target textures and post processes used in the glow layer.
  98427. */
  98428. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  98429. var _this = this;
  98430. var blurTextureWidth = this._mainTextureDesiredSize.width;
  98431. var blurTextureHeight = this._mainTextureDesiredSize.height;
  98432. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98433. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98434. var textureType = 0;
  98435. if (this._engine.getCaps().textureHalfFloatRender) {
  98436. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98437. }
  98438. else {
  98439. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98440. }
  98441. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  98442. width: blurTextureWidth,
  98443. height: blurTextureHeight
  98444. }, this._scene, false, true, textureType);
  98445. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98446. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98447. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98448. this._blurTexture1.renderParticles = false;
  98449. this._blurTexture1.ignoreCameraViewport = true;
  98450. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  98451. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  98452. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  98453. width: blurTextureWidth2,
  98454. height: blurTextureHeight2
  98455. }, this._scene, false, true, textureType);
  98456. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98457. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98458. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98459. this._blurTexture2.renderParticles = false;
  98460. this._blurTexture2.ignoreCameraViewport = true;
  98461. this._textures = [this._blurTexture1, this._blurTexture2];
  98462. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98463. width: blurTextureWidth,
  98464. height: blurTextureHeight
  98465. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98466. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  98467. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  98468. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  98469. effect.setTexture("textureSampler", _this._mainTexture);
  98470. });
  98471. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98472. width: blurTextureWidth,
  98473. height: blurTextureHeight
  98474. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98475. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98476. width: blurTextureWidth2,
  98477. height: blurTextureHeight2
  98478. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98479. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  98480. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  98481. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  98482. effect.setTexture("textureSampler", _this._blurTexture1);
  98483. });
  98484. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98485. width: blurTextureWidth2,
  98486. height: blurTextureHeight2
  98487. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98488. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98489. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  98490. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98491. this._mainTexture.samples = this._options.mainTextureSamples;
  98492. this._mainTexture.onAfterUnbindObservable.add(function () {
  98493. var internalTexture = _this._blurTexture1.getInternalTexture();
  98494. if (internalTexture) {
  98495. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  98496. internalTexture = _this._blurTexture2.getInternalTexture();
  98497. if (internalTexture) {
  98498. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  98499. }
  98500. }
  98501. });
  98502. // Prevent autoClear.
  98503. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98504. };
  98505. /**
  98506. * Checks for the readiness of the element composing the layer.
  98507. * @param subMesh the mesh to check for
  98508. * @param useInstances specify wether or not to use instances to render the mesh
  98509. * @param emissiveTexture the associated emissive texture used to generate the glow
  98510. * @return true if ready otherwise, false
  98511. */
  98512. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  98513. var material = subMesh.getMaterial();
  98514. var mesh = subMesh.getRenderingMesh();
  98515. if (!material || !mesh) {
  98516. return false;
  98517. }
  98518. var emissiveTexture = material.emissiveTexture;
  98519. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98520. };
  98521. /**
  98522. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98523. */
  98524. GlowLayer.prototype.needStencil = function () {
  98525. return false;
  98526. };
  98527. /**
  98528. * Implementation specific of rendering the generating effect on the main canvas.
  98529. * @param effect The effect used to render through
  98530. */
  98531. GlowLayer.prototype._internalRender = function (effect) {
  98532. // Texture
  98533. effect.setTexture("textureSampler", this._blurTexture1);
  98534. effect.setTexture("textureSampler2", this._blurTexture2);
  98535. effect.setFloat("offset", this._intensity);
  98536. // Cache
  98537. var engine = this._engine;
  98538. var previousStencilBuffer = engine.getStencilBuffer();
  98539. // Draw order
  98540. engine.setStencilBuffer(false);
  98541. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98542. // Draw order
  98543. engine.setStencilBuffer(previousStencilBuffer);
  98544. };
  98545. /**
  98546. * Sets the required values for both the emissive texture and and the main color.
  98547. */
  98548. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98549. var textureLevel = 1.0;
  98550. if (this.customEmissiveTextureSelector) {
  98551. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  98552. }
  98553. else {
  98554. if (material) {
  98555. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98556. if (this._emissiveTextureAndColor.texture) {
  98557. textureLevel = this._emissiveTextureAndColor.texture.level;
  98558. }
  98559. }
  98560. else {
  98561. this._emissiveTextureAndColor.texture = null;
  98562. }
  98563. }
  98564. if (this.customEmissiveColorSelector) {
  98565. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  98566. }
  98567. else {
  98568. if (material.emissiveColor) {
  98569. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  98570. }
  98571. else {
  98572. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98573. }
  98574. }
  98575. };
  98576. /**
  98577. * Returns true if the mesh should render, otherwise false.
  98578. * @param mesh The mesh to render
  98579. * @returns true if it should render otherwise false
  98580. */
  98581. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  98582. return this.hasMesh(mesh);
  98583. };
  98584. /**
  98585. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  98586. * @param mesh The mesh to exclude from the glow layer
  98587. */
  98588. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  98589. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  98590. this._excludedMeshes.push(mesh.uniqueId);
  98591. }
  98592. };
  98593. /**
  98594. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  98595. * @param mesh The mesh to remove
  98596. */
  98597. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  98598. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  98599. if (index !== -1) {
  98600. this._excludedMeshes.splice(index, 1);
  98601. }
  98602. };
  98603. /**
  98604. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  98605. * @param mesh The mesh to include in the glow layer
  98606. */
  98607. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  98608. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  98609. this._includedOnlyMeshes.push(mesh.uniqueId);
  98610. }
  98611. };
  98612. /**
  98613. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  98614. * @param mesh The mesh to remove
  98615. */
  98616. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  98617. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  98618. if (index !== -1) {
  98619. this._includedOnlyMeshes.splice(index, 1);
  98620. }
  98621. };
  98622. /**
  98623. * Determine if a given mesh will be used in the glow layer
  98624. * @param mesh The mesh to test
  98625. * @returns true if the mesh will be highlighted by the current glow layer
  98626. */
  98627. GlowLayer.prototype.hasMesh = function (mesh) {
  98628. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98629. return false;
  98630. }
  98631. // Included Mesh
  98632. if (this._includedOnlyMeshes.length) {
  98633. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  98634. }
  98635. ;
  98636. // Excluded Mesh
  98637. if (this._excludedMeshes.length) {
  98638. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  98639. }
  98640. ;
  98641. return true;
  98642. };
  98643. /**
  98644. * Free any resources and references associated to a mesh.
  98645. * Internal use
  98646. * @param mesh The mesh to free.
  98647. */
  98648. GlowLayer.prototype._disposeMesh = function (mesh) {
  98649. this.removeIncludedOnlyMesh(mesh);
  98650. this.removeExcludedMesh(mesh);
  98651. };
  98652. /**
  98653. * Gets the class name of the effect layer
  98654. * @returns the string with the class name of the effect layer
  98655. */
  98656. GlowLayer.prototype.getClassName = function () {
  98657. return "GlowLayer";
  98658. };
  98659. /**
  98660. * Serializes this glow layer
  98661. * @returns a serialized glow layer object
  98662. */
  98663. GlowLayer.prototype.serialize = function () {
  98664. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98665. serializationObject.customType = "BABYLON.GlowLayer";
  98666. var index;
  98667. // Included meshes
  98668. serializationObject.includedMeshes = [];
  98669. if (this._includedOnlyMeshes.length) {
  98670. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  98671. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  98672. if (mesh) {
  98673. serializationObject.includedMeshes.push(mesh.id);
  98674. }
  98675. }
  98676. }
  98677. // Excluded meshes
  98678. serializationObject.excludedMeshes = [];
  98679. if (this._excludedMeshes.length) {
  98680. for (index = 0; index < this._excludedMeshes.length; index++) {
  98681. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  98682. if (mesh) {
  98683. serializationObject.excludedMeshes.push(mesh.id);
  98684. }
  98685. }
  98686. }
  98687. return serializationObject;
  98688. };
  98689. /**
  98690. * Creates a Glow Layer from parsed glow layer data
  98691. * @param parsedGlowLayer defines glow layer data
  98692. * @param scene defines the current scene
  98693. * @param rootUrl defines the root URL containing the glow layer information
  98694. * @returns a parsed Glow Layer
  98695. */
  98696. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  98697. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  98698. var index;
  98699. // Excluded meshes
  98700. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  98701. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  98702. if (mesh) {
  98703. gl.addExcludedMesh(mesh);
  98704. }
  98705. }
  98706. // Included meshes
  98707. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  98708. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  98709. if (mesh) {
  98710. gl.addIncludedOnlyMesh(mesh);
  98711. }
  98712. }
  98713. return gl;
  98714. };
  98715. /**
  98716. * Effect Name of the layer.
  98717. */
  98718. GlowLayer.EffectName = "GlowLayer";
  98719. /**
  98720. * The default blur kernel size used for the glow.
  98721. */
  98722. GlowLayer.DefaultBlurKernelSize = 32;
  98723. /**
  98724. * The default texture size ratio used for the glow.
  98725. */
  98726. GlowLayer.DefaultTextureRatio = 0.5;
  98727. __decorate([
  98728. BABYLON.serialize()
  98729. ], GlowLayer.prototype, "blurKernelSize", null);
  98730. __decorate([
  98731. BABYLON.serialize()
  98732. ], GlowLayer.prototype, "intensity", null);
  98733. __decorate([
  98734. BABYLON.serialize("options")
  98735. ], GlowLayer.prototype, "_options", void 0);
  98736. return GlowLayer;
  98737. }(BABYLON.EffectLayer));
  98738. BABYLON.GlowLayer = GlowLayer;
  98739. })(BABYLON || (BABYLON = {}));
  98740. //# sourceMappingURL=babylon.glowLayer.js.map
  98741. var BABYLON;
  98742. (function (BABYLON) {
  98743. /**
  98744. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  98745. */
  98746. var AssetTaskState;
  98747. (function (AssetTaskState) {
  98748. /**
  98749. * Initialization
  98750. */
  98751. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  98752. /**
  98753. * Running
  98754. */
  98755. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  98756. /**
  98757. * Done
  98758. */
  98759. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  98760. /**
  98761. * Error
  98762. */
  98763. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  98764. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  98765. /**
  98766. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  98767. */
  98768. var AbstractAssetTask = /** @class */ (function () {
  98769. /**
  98770. * Creates a new {BABYLON.AssetsManager}
  98771. * @param name defines the name of the task
  98772. */
  98773. function AbstractAssetTask(
  98774. /**
  98775. * Task name
  98776. */ name) {
  98777. this.name = name;
  98778. this._isCompleted = false;
  98779. this._taskState = AssetTaskState.INIT;
  98780. }
  98781. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98782. /**
  98783. * Get if the task is completed
  98784. */
  98785. get: function () {
  98786. return this._isCompleted;
  98787. },
  98788. enumerable: true,
  98789. configurable: true
  98790. });
  98791. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98792. /**
  98793. * Gets the current state of the task
  98794. */
  98795. get: function () {
  98796. return this._taskState;
  98797. },
  98798. enumerable: true,
  98799. configurable: true
  98800. });
  98801. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98802. /**
  98803. * Gets the current error object (if task is in error)
  98804. */
  98805. get: function () {
  98806. return this._errorObject;
  98807. },
  98808. enumerable: true,
  98809. configurable: true
  98810. });
  98811. /**
  98812. * Internal only
  98813. * @hidden
  98814. */
  98815. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98816. if (this._errorObject) {
  98817. return;
  98818. }
  98819. this._errorObject = {
  98820. message: message,
  98821. exception: exception
  98822. };
  98823. };
  98824. /**
  98825. * Execute the current task
  98826. * @param scene defines the scene where you want your assets to be loaded
  98827. * @param onSuccess is a callback called when the task is successfully executed
  98828. * @param onError is a callback called if an error occurs
  98829. */
  98830. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98831. var _this = this;
  98832. this._taskState = AssetTaskState.RUNNING;
  98833. this.runTask(scene, function () {
  98834. _this.onDoneCallback(onSuccess, onError);
  98835. }, function (msg, exception) {
  98836. _this.onErrorCallback(onError, msg, exception);
  98837. });
  98838. };
  98839. /**
  98840. * Execute the current task
  98841. * @param scene defines the scene where you want your assets to be loaded
  98842. * @param onSuccess is a callback called when the task is successfully executed
  98843. * @param onError is a callback called if an error occurs
  98844. */
  98845. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98846. throw new Error("runTask is not implemented");
  98847. };
  98848. /**
  98849. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98850. * This can be used with failed tasks that have the reason for failure fixed.
  98851. */
  98852. AbstractAssetTask.prototype.reset = function () {
  98853. this._taskState = AssetTaskState.INIT;
  98854. };
  98855. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98856. this._taskState = AssetTaskState.ERROR;
  98857. this._errorObject = {
  98858. message: message,
  98859. exception: exception
  98860. };
  98861. if (this.onError) {
  98862. this.onError(this, message, exception);
  98863. }
  98864. onError();
  98865. };
  98866. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98867. try {
  98868. this._taskState = AssetTaskState.DONE;
  98869. this._isCompleted = true;
  98870. if (this.onSuccess) {
  98871. this.onSuccess(this);
  98872. }
  98873. onSuccess();
  98874. }
  98875. catch (e) {
  98876. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98877. }
  98878. };
  98879. return AbstractAssetTask;
  98880. }());
  98881. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98882. /**
  98883. * Class used to share progress information about assets loading
  98884. */
  98885. var AssetsProgressEvent = /** @class */ (function () {
  98886. /**
  98887. * Creates a {BABYLON.AssetsProgressEvent}
  98888. * @param remainingCount defines the number of remaining tasks to process
  98889. * @param totalCount defines the total number of tasks
  98890. * @param task defines the task that was just processed
  98891. */
  98892. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98893. this.remainingCount = remainingCount;
  98894. this.totalCount = totalCount;
  98895. this.task = task;
  98896. }
  98897. return AssetsProgressEvent;
  98898. }());
  98899. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98900. /**
  98901. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98902. */
  98903. var MeshAssetTask = /** @class */ (function (_super) {
  98904. __extends(MeshAssetTask, _super);
  98905. /**
  98906. * Creates a new {BABYLON.MeshAssetTask}
  98907. * @param name defines the name of the task
  98908. * @param meshesNames defines the list of mesh's names you want to load
  98909. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98910. * @param sceneFilename defines the filename of the scene to load from
  98911. */
  98912. function MeshAssetTask(
  98913. /**
  98914. * Defines the name of the task
  98915. */
  98916. name,
  98917. /**
  98918. * Defines the list of mesh's names you want to load
  98919. */
  98920. meshesNames,
  98921. /**
  98922. * Defines the root url to use as a base to load your meshes and associated resources
  98923. */
  98924. rootUrl,
  98925. /**
  98926. * Defines the filename of the scene to load from
  98927. */
  98928. sceneFilename) {
  98929. var _this = _super.call(this, name) || this;
  98930. _this.name = name;
  98931. _this.meshesNames = meshesNames;
  98932. _this.rootUrl = rootUrl;
  98933. _this.sceneFilename = sceneFilename;
  98934. return _this;
  98935. }
  98936. /**
  98937. * Execute the current task
  98938. * @param scene defines the scene where you want your assets to be loaded
  98939. * @param onSuccess is a callback called when the task is successfully executed
  98940. * @param onError is a callback called if an error occurs
  98941. */
  98942. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98943. var _this = this;
  98944. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98945. _this.loadedMeshes = meshes;
  98946. _this.loadedParticleSystems = particleSystems;
  98947. _this.loadedSkeletons = skeletons;
  98948. onSuccess();
  98949. }, null, function (scene, message, exception) {
  98950. onError(message, exception);
  98951. });
  98952. };
  98953. return MeshAssetTask;
  98954. }(AbstractAssetTask));
  98955. BABYLON.MeshAssetTask = MeshAssetTask;
  98956. /**
  98957. * Define a task used by {BABYLON.AssetsManager} to load text content
  98958. */
  98959. var TextFileAssetTask = /** @class */ (function (_super) {
  98960. __extends(TextFileAssetTask, _super);
  98961. /**
  98962. * Creates a new TextFileAssetTask object
  98963. * @param name defines the name of the task
  98964. * @param url defines the location of the file to load
  98965. */
  98966. function TextFileAssetTask(
  98967. /**
  98968. * Defines the name of the task
  98969. */
  98970. name,
  98971. /**
  98972. * Defines the location of the file to load
  98973. */
  98974. url) {
  98975. var _this = _super.call(this, name) || this;
  98976. _this.name = name;
  98977. _this.url = url;
  98978. return _this;
  98979. }
  98980. /**
  98981. * Execute the current task
  98982. * @param scene defines the scene where you want your assets to be loaded
  98983. * @param onSuccess is a callback called when the task is successfully executed
  98984. * @param onError is a callback called if an error occurs
  98985. */
  98986. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98987. var _this = this;
  98988. scene._loadFile(this.url, function (data) {
  98989. _this.text = data;
  98990. onSuccess();
  98991. }, undefined, false, false, function (request, exception) {
  98992. if (request) {
  98993. onError(request.status + " " + request.statusText, exception);
  98994. }
  98995. });
  98996. };
  98997. return TextFileAssetTask;
  98998. }(AbstractAssetTask));
  98999. BABYLON.TextFileAssetTask = TextFileAssetTask;
  99000. /**
  99001. * Define a task used by {BABYLON.AssetsManager} to load binary data
  99002. */
  99003. var BinaryFileAssetTask = /** @class */ (function (_super) {
  99004. __extends(BinaryFileAssetTask, _super);
  99005. /**
  99006. * Creates a new BinaryFileAssetTask object
  99007. * @param name defines the name of the new task
  99008. * @param url defines the location of the file to load
  99009. */
  99010. function BinaryFileAssetTask(
  99011. /**
  99012. * Defines the name of the task
  99013. */
  99014. name,
  99015. /**
  99016. * Defines the location of the file to load
  99017. */
  99018. url) {
  99019. var _this = _super.call(this, name) || this;
  99020. _this.name = name;
  99021. _this.url = url;
  99022. return _this;
  99023. }
  99024. /**
  99025. * Execute the current task
  99026. * @param scene defines the scene where you want your assets to be loaded
  99027. * @param onSuccess is a callback called when the task is successfully executed
  99028. * @param onError is a callback called if an error occurs
  99029. */
  99030. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99031. var _this = this;
  99032. scene._loadFile(this.url, function (data) {
  99033. _this.data = data;
  99034. onSuccess();
  99035. }, undefined, true, true, function (request, exception) {
  99036. if (request) {
  99037. onError(request.status + " " + request.statusText, exception);
  99038. }
  99039. });
  99040. };
  99041. return BinaryFileAssetTask;
  99042. }(AbstractAssetTask));
  99043. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  99044. /**
  99045. * Define a task used by {BABYLON.AssetsManager} to load images
  99046. */
  99047. var ImageAssetTask = /** @class */ (function (_super) {
  99048. __extends(ImageAssetTask, _super);
  99049. /**
  99050. * Creates a new ImageAssetTask
  99051. * @param name defines the name of the task
  99052. * @param url defines the location of the image to load
  99053. */
  99054. function ImageAssetTask(
  99055. /**
  99056. * Defines the name of the task
  99057. */
  99058. name,
  99059. /**
  99060. * Defines the location of the image to load
  99061. */
  99062. url) {
  99063. var _this = _super.call(this, name) || this;
  99064. _this.name = name;
  99065. _this.url = url;
  99066. return _this;
  99067. }
  99068. /**
  99069. * Execute the current task
  99070. * @param scene defines the scene where you want your assets to be loaded
  99071. * @param onSuccess is a callback called when the task is successfully executed
  99072. * @param onError is a callback called if an error occurs
  99073. */
  99074. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99075. var _this = this;
  99076. var img = new Image();
  99077. BABYLON.Tools.SetCorsBehavior(this.url, img);
  99078. img.onload = function () {
  99079. _this.image = img;
  99080. onSuccess();
  99081. };
  99082. img.onerror = function (err) {
  99083. onError("Error loading image", err);
  99084. };
  99085. img.src = this.url;
  99086. };
  99087. return ImageAssetTask;
  99088. }(AbstractAssetTask));
  99089. BABYLON.ImageAssetTask = ImageAssetTask;
  99090. /**
  99091. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  99092. */
  99093. var TextureAssetTask = /** @class */ (function (_super) {
  99094. __extends(TextureAssetTask, _super);
  99095. /**
  99096. * Creates a new TextureAssetTask object
  99097. * @param name defines the name of the task
  99098. * @param url defines the location of the file to load
  99099. * @param noMipmap defines if mipmap should not be generated (default is false)
  99100. * @param invertY defines if texture must be inverted on Y axis (default is false)
  99101. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99102. */
  99103. function TextureAssetTask(
  99104. /**
  99105. * Defines the name of the task
  99106. */
  99107. name,
  99108. /**
  99109. * Defines the location of the file to load
  99110. */
  99111. url,
  99112. /**
  99113. * Defines if mipmap should not be generated (default is false)
  99114. */
  99115. noMipmap,
  99116. /**
  99117. * Defines if texture must be inverted on Y axis (default is false)
  99118. */
  99119. invertY,
  99120. /**
  99121. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99122. */
  99123. samplingMode) {
  99124. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99125. var _this = _super.call(this, name) || this;
  99126. _this.name = name;
  99127. _this.url = url;
  99128. _this.noMipmap = noMipmap;
  99129. _this.invertY = invertY;
  99130. _this.samplingMode = samplingMode;
  99131. return _this;
  99132. }
  99133. /**
  99134. * Execute the current task
  99135. * @param scene defines the scene where you want your assets to be loaded
  99136. * @param onSuccess is a callback called when the task is successfully executed
  99137. * @param onError is a callback called if an error occurs
  99138. */
  99139. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99140. var onload = function () {
  99141. onSuccess();
  99142. };
  99143. var onerror = function (message, exception) {
  99144. onError(message, exception);
  99145. };
  99146. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  99147. };
  99148. return TextureAssetTask;
  99149. }(AbstractAssetTask));
  99150. BABYLON.TextureAssetTask = TextureAssetTask;
  99151. /**
  99152. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  99153. */
  99154. var CubeTextureAssetTask = /** @class */ (function (_super) {
  99155. __extends(CubeTextureAssetTask, _super);
  99156. /**
  99157. * Creates a new CubeTextureAssetTask
  99158. * @param name defines the name of the task
  99159. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99160. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99161. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99162. * @param files defines the explicit list of files (undefined by default)
  99163. */
  99164. function CubeTextureAssetTask(
  99165. /**
  99166. * Defines the name of the task
  99167. */
  99168. name,
  99169. /**
  99170. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99171. */
  99172. url,
  99173. /**
  99174. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99175. */
  99176. extensions,
  99177. /**
  99178. * Defines if mipmaps should not be generated (default is false)
  99179. */
  99180. noMipmap,
  99181. /**
  99182. * Defines the explicit list of files (undefined by default)
  99183. */
  99184. files) {
  99185. var _this = _super.call(this, name) || this;
  99186. _this.name = name;
  99187. _this.url = url;
  99188. _this.extensions = extensions;
  99189. _this.noMipmap = noMipmap;
  99190. _this.files = files;
  99191. return _this;
  99192. }
  99193. /**
  99194. * Execute the current task
  99195. * @param scene defines the scene where you want your assets to be loaded
  99196. * @param onSuccess is a callback called when the task is successfully executed
  99197. * @param onError is a callback called if an error occurs
  99198. */
  99199. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99200. var onload = function () {
  99201. onSuccess();
  99202. };
  99203. var onerror = function (message, exception) {
  99204. onError(message, exception);
  99205. };
  99206. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  99207. };
  99208. return CubeTextureAssetTask;
  99209. }(AbstractAssetTask));
  99210. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  99211. /**
  99212. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  99213. */
  99214. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  99215. __extends(HDRCubeTextureAssetTask, _super);
  99216. /**
  99217. * Creates a new HDRCubeTextureAssetTask object
  99218. * @param name defines the name of the task
  99219. * @param url defines the location of the file to load
  99220. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  99221. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99222. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99223. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  99224. * @param reserved Internal use only
  99225. */
  99226. function HDRCubeTextureAssetTask(
  99227. /**
  99228. * Defines the name of the task
  99229. */
  99230. name,
  99231. /**
  99232. * Defines the location of the file to load
  99233. */
  99234. url,
  99235. /**
  99236. * Defines the desired size (the more it increases the longer the generation will be)
  99237. */
  99238. size,
  99239. /**
  99240. * Defines if mipmaps should not be generated (default is false)
  99241. */
  99242. noMipmap,
  99243. /**
  99244. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99245. */
  99246. generateHarmonics,
  99247. /**
  99248. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  99249. */
  99250. gammaSpace,
  99251. /**
  99252. * Internal Use Only
  99253. */
  99254. reserved) {
  99255. if (noMipmap === void 0) { noMipmap = false; }
  99256. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99257. if (gammaSpace === void 0) { gammaSpace = false; }
  99258. if (reserved === void 0) { reserved = false; }
  99259. var _this = _super.call(this, name) || this;
  99260. _this.name = name;
  99261. _this.url = url;
  99262. _this.size = size;
  99263. _this.noMipmap = noMipmap;
  99264. _this.generateHarmonics = generateHarmonics;
  99265. _this.gammaSpace = gammaSpace;
  99266. _this.reserved = reserved;
  99267. return _this;
  99268. }
  99269. /**
  99270. * Execute the current task
  99271. * @param scene defines the scene where you want your assets to be loaded
  99272. * @param onSuccess is a callback called when the task is successfully executed
  99273. * @param onError is a callback called if an error occurs
  99274. */
  99275. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99276. var onload = function () {
  99277. onSuccess();
  99278. };
  99279. var onerror = function (message, exception) {
  99280. onError(message, exception);
  99281. };
  99282. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  99283. };
  99284. return HDRCubeTextureAssetTask;
  99285. }(AbstractAssetTask));
  99286. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  99287. /**
  99288. * This class can be used to easily import assets into a scene
  99289. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  99290. */
  99291. var AssetsManager = /** @class */ (function () {
  99292. /**
  99293. * Creates a new AssetsManager
  99294. * @param scene defines the scene to work on
  99295. */
  99296. function AssetsManager(scene) {
  99297. this._isLoading = false;
  99298. this._tasks = new Array();
  99299. this._waitingTasksCount = 0;
  99300. this._totalTasksCount = 0;
  99301. /**
  99302. * Observable called when all tasks are processed
  99303. */
  99304. this.onTaskSuccessObservable = new BABYLON.Observable();
  99305. /**
  99306. * Observable called when a task had an error
  99307. */
  99308. this.onTaskErrorObservable = new BABYLON.Observable();
  99309. /**
  99310. * Observable called when a task is successful
  99311. */
  99312. this.onTasksDoneObservable = new BABYLON.Observable();
  99313. /**
  99314. * Observable called when a task is done (whatever the result is)
  99315. */
  99316. this.onProgressObservable = new BABYLON.Observable();
  99317. /**
  99318. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  99319. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  99320. */
  99321. this.useDefaultLoadingScreen = true;
  99322. this._scene = scene;
  99323. }
  99324. /**
  99325. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  99326. * @param taskName defines the name of the new task
  99327. * @param meshesNames defines the name of meshes to load
  99328. * @param rootUrl defines the root url to use to locate files
  99329. * @param sceneFilename defines the filename of the scene file
  99330. * @returns a new {BABYLON.MeshAssetTask} object
  99331. */
  99332. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  99333. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  99334. this._tasks.push(task);
  99335. return task;
  99336. };
  99337. /**
  99338. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  99339. * @param taskName defines the name of the new task
  99340. * @param url defines the url of the file to load
  99341. * @returns a new {BABYLON.TextFileAssetTask} object
  99342. */
  99343. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  99344. var task = new TextFileAssetTask(taskName, url);
  99345. this._tasks.push(task);
  99346. return task;
  99347. };
  99348. /**
  99349. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  99350. * @param taskName defines the name of the new task
  99351. * @param url defines the url of the file to load
  99352. * @returns a new {BABYLON.BinaryFileAssetTask} object
  99353. */
  99354. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  99355. var task = new BinaryFileAssetTask(taskName, url);
  99356. this._tasks.push(task);
  99357. return task;
  99358. };
  99359. /**
  99360. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  99361. * @param taskName defines the name of the new task
  99362. * @param url defines the url of the file to load
  99363. * @returns a new {BABYLON.ImageAssetTask} object
  99364. */
  99365. AssetsManager.prototype.addImageTask = function (taskName, url) {
  99366. var task = new ImageAssetTask(taskName, url);
  99367. this._tasks.push(task);
  99368. return task;
  99369. };
  99370. /**
  99371. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  99372. * @param taskName defines the name of the new task
  99373. * @param url defines the url of the file to load
  99374. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99375. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  99376. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  99377. * @returns a new {BABYLON.TextureAssetTask} object
  99378. */
  99379. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  99380. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99381. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  99382. this._tasks.push(task);
  99383. return task;
  99384. };
  99385. /**
  99386. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  99387. * @param taskName defines the name of the new task
  99388. * @param url defines the url of the file to load
  99389. * @param extensions defines the extension to use to load the cube map (can be null)
  99390. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99391. * @param files defines the list of files to load (can be null)
  99392. * @returns a new {BABYLON.CubeTextureAssetTask} object
  99393. */
  99394. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  99395. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  99396. this._tasks.push(task);
  99397. return task;
  99398. };
  99399. /**
  99400. *
  99401. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  99402. * @param taskName defines the name of the new task
  99403. * @param url defines the url of the file to load
  99404. * @param size defines the size you want for the cubemap (can be null)
  99405. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99406. * @param generateHarmonics defines if you want to automatically generate (true by default)
  99407. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  99408. * @param reserved Internal use only
  99409. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  99410. */
  99411. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  99412. if (noMipmap === void 0) { noMipmap = false; }
  99413. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99414. if (gammaSpace === void 0) { gammaSpace = false; }
  99415. if (reserved === void 0) { reserved = false; }
  99416. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  99417. this._tasks.push(task);
  99418. return task;
  99419. };
  99420. /**
  99421. * Remove a task from the assets manager.
  99422. * @param task the task to remove
  99423. */
  99424. AssetsManager.prototype.removeTask = function (task) {
  99425. var index = this._tasks.indexOf(task);
  99426. if (index > -1) {
  99427. this._tasks.splice(index, 1);
  99428. }
  99429. };
  99430. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  99431. this._waitingTasksCount--;
  99432. try {
  99433. if (this.onProgress) {
  99434. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  99435. }
  99436. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  99437. }
  99438. catch (e) {
  99439. BABYLON.Tools.Error("Error running progress callbacks.");
  99440. console.log(e);
  99441. }
  99442. if (this._waitingTasksCount === 0) {
  99443. try {
  99444. if (this.onFinish) {
  99445. this.onFinish(this._tasks);
  99446. }
  99447. // Let's remove successfull tasks
  99448. var currentTasks = this._tasks.slice();
  99449. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  99450. var task = currentTasks_1[_i];
  99451. if (task.taskState === AssetTaskState.DONE) {
  99452. var index = this._tasks.indexOf(task);
  99453. if (index > -1) {
  99454. this._tasks.splice(index, 1);
  99455. }
  99456. }
  99457. }
  99458. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99459. }
  99460. catch (e) {
  99461. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  99462. console.log(e);
  99463. }
  99464. this._isLoading = false;
  99465. this._scene.getEngine().hideLoadingUI();
  99466. }
  99467. };
  99468. AssetsManager.prototype._runTask = function (task) {
  99469. var _this = this;
  99470. var done = function () {
  99471. try {
  99472. if (_this.onTaskSuccess) {
  99473. _this.onTaskSuccess(task);
  99474. }
  99475. _this.onTaskSuccessObservable.notifyObservers(task);
  99476. _this._decreaseWaitingTasksCount(task);
  99477. }
  99478. catch (e) {
  99479. error("Error executing task success callbacks", e);
  99480. }
  99481. };
  99482. var error = function (message, exception) {
  99483. task._setErrorObject(message, exception);
  99484. if (_this.onTaskError) {
  99485. _this.onTaskError(task);
  99486. }
  99487. _this.onTaskErrorObservable.notifyObservers(task);
  99488. _this._decreaseWaitingTasksCount(task);
  99489. };
  99490. task.run(this._scene, done, error);
  99491. };
  99492. /**
  99493. * Reset the {BABYLON.AssetsManager} and remove all tasks
  99494. * @return the current instance of the {BABYLON.AssetsManager}
  99495. */
  99496. AssetsManager.prototype.reset = function () {
  99497. this._isLoading = false;
  99498. this._tasks = new Array();
  99499. return this;
  99500. };
  99501. /**
  99502. * Start the loading process
  99503. * @return the current instance of the {BABYLON.AssetsManager}
  99504. */
  99505. AssetsManager.prototype.load = function () {
  99506. if (this._isLoading) {
  99507. return this;
  99508. }
  99509. this._isLoading = true;
  99510. this._waitingTasksCount = this._tasks.length;
  99511. this._totalTasksCount = this._tasks.length;
  99512. if (this._waitingTasksCount === 0) {
  99513. this._isLoading = false;
  99514. if (this.onFinish) {
  99515. this.onFinish(this._tasks);
  99516. }
  99517. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99518. return this;
  99519. }
  99520. if (this.useDefaultLoadingScreen) {
  99521. this._scene.getEngine().displayLoadingUI();
  99522. }
  99523. for (var index = 0; index < this._tasks.length; index++) {
  99524. var task = this._tasks[index];
  99525. if (task.taskState === AssetTaskState.INIT) {
  99526. this._runTask(task);
  99527. }
  99528. }
  99529. return this;
  99530. };
  99531. return AssetsManager;
  99532. }());
  99533. BABYLON.AssetsManager = AssetsManager;
  99534. })(BABYLON || (BABYLON = {}));
  99535. //# sourceMappingURL=babylon.assetsManager.js.map
  99536. var BABYLON;
  99537. (function (BABYLON) {
  99538. var serializedGeometries = [];
  99539. var serializeGeometry = function (geometry, serializationGeometries) {
  99540. if (serializedGeometries[geometry.id]) {
  99541. return;
  99542. }
  99543. if (geometry.doNotSerialize) {
  99544. return;
  99545. }
  99546. if (geometry instanceof BABYLON.BoxGeometry) {
  99547. serializationGeometries.boxes.push(geometry.serialize());
  99548. }
  99549. else if (geometry instanceof BABYLON.SphereGeometry) {
  99550. serializationGeometries.spheres.push(geometry.serialize());
  99551. }
  99552. else if (geometry instanceof BABYLON.CylinderGeometry) {
  99553. serializationGeometries.cylinders.push(geometry.serialize());
  99554. }
  99555. else if (geometry instanceof BABYLON.TorusGeometry) {
  99556. serializationGeometries.toruses.push(geometry.serialize());
  99557. }
  99558. else if (geometry instanceof BABYLON.GroundGeometry) {
  99559. serializationGeometries.grounds.push(geometry.serialize());
  99560. }
  99561. else if (geometry instanceof BABYLON.Plane) {
  99562. serializationGeometries.planes.push(geometry.serialize());
  99563. }
  99564. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  99565. serializationGeometries.torusKnots.push(geometry.serialize());
  99566. }
  99567. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  99568. throw new Error("Unknown primitive type");
  99569. }
  99570. else {
  99571. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  99572. }
  99573. serializedGeometries[geometry.id] = true;
  99574. };
  99575. var serializeMesh = function (mesh, serializationScene) {
  99576. var serializationObject = {};
  99577. // Geometry
  99578. var geometry = mesh._geometry;
  99579. if (geometry) {
  99580. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  99581. // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  99582. serializeGeometry(geometry, serializationScene.geometries);
  99583. }
  99584. }
  99585. // Custom
  99586. if (mesh.serialize) {
  99587. mesh.serialize(serializationObject);
  99588. }
  99589. return serializationObject;
  99590. };
  99591. var finalizeSingleMesh = function (mesh, serializationObject) {
  99592. //only works if the mesh is already loaded
  99593. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99594. //serialize material
  99595. if (mesh.material) {
  99596. if (mesh.material instanceof BABYLON.MultiMaterial) {
  99597. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  99598. serializationObject.materials = serializationObject.materials || [];
  99599. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99600. serializationObject.multiMaterials.push(mesh.material.serialize());
  99601. var _loop_1 = function (submaterial) {
  99602. if (submaterial) {
  99603. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  99604. serializationObject.materials.push(submaterial.serialize());
  99605. }
  99606. }
  99607. };
  99608. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  99609. var submaterial = _a[_i];
  99610. _loop_1(submaterial);
  99611. }
  99612. }
  99613. }
  99614. else {
  99615. serializationObject.materials = serializationObject.materials || [];
  99616. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99617. serializationObject.materials.push(mesh.material.serialize());
  99618. }
  99619. }
  99620. }
  99621. //serialize geometry
  99622. var geometry = mesh._geometry;
  99623. if (geometry) {
  99624. if (!serializationObject.geometries) {
  99625. serializationObject.geometries = {};
  99626. serializationObject.geometries.boxes = [];
  99627. serializationObject.geometries.spheres = [];
  99628. serializationObject.geometries.cylinders = [];
  99629. serializationObject.geometries.toruses = [];
  99630. serializationObject.geometries.grounds = [];
  99631. serializationObject.geometries.planes = [];
  99632. serializationObject.geometries.torusKnots = [];
  99633. serializationObject.geometries.vertexData = [];
  99634. }
  99635. serializeGeometry(geometry, serializationObject.geometries);
  99636. }
  99637. // Skeletons
  99638. if (mesh.skeleton) {
  99639. serializationObject.skeletons = serializationObject.skeletons || [];
  99640. serializationObject.skeletons.push(mesh.skeleton.serialize());
  99641. }
  99642. //serialize the actual mesh
  99643. serializationObject.meshes = serializationObject.meshes || [];
  99644. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99645. }
  99646. };
  99647. var SceneSerializer = /** @class */ (function () {
  99648. function SceneSerializer() {
  99649. }
  99650. SceneSerializer.ClearCache = function () {
  99651. serializedGeometries = [];
  99652. };
  99653. SceneSerializer.Serialize = function (scene) {
  99654. var serializationObject = {};
  99655. SceneSerializer.ClearCache();
  99656. // Scene
  99657. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  99658. serializationObject.autoClear = scene.autoClear;
  99659. serializationObject.clearColor = scene.clearColor.asArray();
  99660. serializationObject.ambientColor = scene.ambientColor.asArray();
  99661. serializationObject.gravity = scene.gravity.asArray();
  99662. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  99663. serializationObject.workerCollisions = scene.workerCollisions;
  99664. // Fog
  99665. if (scene.fogMode && scene.fogMode !== 0) {
  99666. serializationObject.fogMode = scene.fogMode;
  99667. serializationObject.fogColor = scene.fogColor.asArray();
  99668. serializationObject.fogStart = scene.fogStart;
  99669. serializationObject.fogEnd = scene.fogEnd;
  99670. serializationObject.fogDensity = scene.fogDensity;
  99671. }
  99672. //Physics
  99673. if (scene.isPhysicsEnabled()) {
  99674. var physicEngine = scene.getPhysicsEngine();
  99675. if (physicEngine) {
  99676. serializationObject.physicsEnabled = true;
  99677. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  99678. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  99679. }
  99680. }
  99681. // Metadata
  99682. if (scene.metadata) {
  99683. serializationObject.metadata = scene.metadata;
  99684. }
  99685. // Morph targets
  99686. serializationObject.morphTargetManagers = [];
  99687. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  99688. var abstractMesh = _a[_i];
  99689. var manager = abstractMesh.morphTargetManager;
  99690. if (manager) {
  99691. serializationObject.morphTargetManagers.push(manager.serialize());
  99692. }
  99693. }
  99694. // Lights
  99695. serializationObject.lights = [];
  99696. var index;
  99697. var light;
  99698. for (index = 0; index < scene.lights.length; index++) {
  99699. light = scene.lights[index];
  99700. if (!light.doNotSerialize) {
  99701. serializationObject.lights.push(light.serialize());
  99702. }
  99703. }
  99704. // Cameras
  99705. serializationObject.cameras = [];
  99706. for (index = 0; index < scene.cameras.length; index++) {
  99707. var camera = scene.cameras[index];
  99708. if (!camera.doNotSerialize) {
  99709. serializationObject.cameras.push(camera.serialize());
  99710. }
  99711. }
  99712. if (scene.activeCamera) {
  99713. serializationObject.activeCameraID = scene.activeCamera.id;
  99714. }
  99715. // Animations
  99716. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  99717. // Materials
  99718. serializationObject.materials = [];
  99719. serializationObject.multiMaterials = [];
  99720. var material;
  99721. for (index = 0; index < scene.materials.length; index++) {
  99722. material = scene.materials[index];
  99723. if (!material.doNotSerialize) {
  99724. serializationObject.materials.push(material.serialize());
  99725. }
  99726. }
  99727. // MultiMaterials
  99728. serializationObject.multiMaterials = [];
  99729. for (index = 0; index < scene.multiMaterials.length; index++) {
  99730. var multiMaterial = scene.multiMaterials[index];
  99731. serializationObject.multiMaterials.push(multiMaterial.serialize());
  99732. }
  99733. // Environment texture
  99734. if (scene.environmentTexture) {
  99735. serializationObject.environmentTexture = scene.environmentTexture.name;
  99736. }
  99737. // Skeletons
  99738. serializationObject.skeletons = [];
  99739. for (index = 0; index < scene.skeletons.length; index++) {
  99740. var skeleton = scene.skeletons[index];
  99741. if (!skeleton.doNotSerialize) {
  99742. serializationObject.skeletons.push(skeleton.serialize());
  99743. }
  99744. }
  99745. // Transform nodes
  99746. serializationObject.transformNodes = [];
  99747. for (index = 0; index < scene.transformNodes.length; index++) {
  99748. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  99749. }
  99750. // Geometries
  99751. serializationObject.geometries = {};
  99752. serializationObject.geometries.boxes = [];
  99753. serializationObject.geometries.spheres = [];
  99754. serializationObject.geometries.cylinders = [];
  99755. serializationObject.geometries.toruses = [];
  99756. serializationObject.geometries.grounds = [];
  99757. serializationObject.geometries.planes = [];
  99758. serializationObject.geometries.torusKnots = [];
  99759. serializationObject.geometries.vertexData = [];
  99760. serializedGeometries = [];
  99761. var geometries = scene.getGeometries();
  99762. for (index = 0; index < geometries.length; index++) {
  99763. var geometry = geometries[index];
  99764. if (geometry.isReady()) {
  99765. serializeGeometry(geometry, serializationObject.geometries);
  99766. }
  99767. }
  99768. // Meshes
  99769. serializationObject.meshes = [];
  99770. for (index = 0; index < scene.meshes.length; index++) {
  99771. var abstractMesh = scene.meshes[index];
  99772. if (abstractMesh instanceof BABYLON.Mesh) {
  99773. var mesh = abstractMesh;
  99774. if (!mesh.doNotSerialize) {
  99775. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99776. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99777. }
  99778. }
  99779. }
  99780. }
  99781. // Particles Systems
  99782. serializationObject.particleSystems = [];
  99783. for (index = 0; index < scene.particleSystems.length; index++) {
  99784. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  99785. }
  99786. // Shadows
  99787. serializationObject.shadowGenerators = [];
  99788. for (index = 0; index < scene.lights.length; index++) {
  99789. light = scene.lights[index];
  99790. var shadowGenerator = light.getShadowGenerator();
  99791. if (shadowGenerator) {
  99792. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  99793. }
  99794. }
  99795. // Action Manager
  99796. if (scene.actionManager) {
  99797. serializationObject.actions = scene.actionManager.serialize("scene");
  99798. }
  99799. // Audio
  99800. serializationObject.sounds = [];
  99801. for (index = 0; index < scene.soundTracks.length; index++) {
  99802. var soundtrack = scene.soundTracks[index];
  99803. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99804. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99805. }
  99806. }
  99807. // Components
  99808. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99809. var component = _c[_b];
  99810. component.serialize(serializationObject);
  99811. }
  99812. return serializationObject;
  99813. };
  99814. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99815. if (withParents === void 0) { withParents = false; }
  99816. if (withChildren === void 0) { withChildren = false; }
  99817. var serializationObject = {};
  99818. SceneSerializer.ClearCache();
  99819. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99820. if (withParents || withChildren) {
  99821. //deliberate for loop! not for each, appended should be processed as well.
  99822. for (var i = 0; i < toSerialize.length; ++i) {
  99823. if (withChildren) {
  99824. toSerialize[i].getDescendants().forEach(function (node) {
  99825. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99826. toSerialize.push(node);
  99827. }
  99828. });
  99829. }
  99830. //make sure the array doesn't contain the object already
  99831. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99832. toSerialize.push(toSerialize[i].parent);
  99833. }
  99834. }
  99835. }
  99836. toSerialize.forEach(function (mesh) {
  99837. finalizeSingleMesh(mesh, serializationObject);
  99838. });
  99839. return serializationObject;
  99840. };
  99841. return SceneSerializer;
  99842. }());
  99843. BABYLON.SceneSerializer = SceneSerializer;
  99844. })(BABYLON || (BABYLON = {}));
  99845. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99846. var BABYLON;
  99847. (function (BABYLON) {
  99848. var ReflectionProbe = /** @class */ (function () {
  99849. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99850. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99851. var _this = this;
  99852. this.name = name;
  99853. this._viewMatrix = BABYLON.Matrix.Identity();
  99854. this._target = BABYLON.Vector3.Zero();
  99855. this._add = BABYLON.Vector3.Zero();
  99856. this._invertYAxis = false;
  99857. this.position = BABYLON.Vector3.Zero();
  99858. this._scene = scene;
  99859. this._scene.reflectionProbes.push(this);
  99860. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99861. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99862. switch (faceIndex) {
  99863. case 0:
  99864. _this._add.copyFromFloats(1, 0, 0);
  99865. break;
  99866. case 1:
  99867. _this._add.copyFromFloats(-1, 0, 0);
  99868. break;
  99869. case 2:
  99870. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99871. break;
  99872. case 3:
  99873. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99874. break;
  99875. case 4:
  99876. _this._add.copyFromFloats(0, 0, 1);
  99877. break;
  99878. case 5:
  99879. _this._add.copyFromFloats(0, 0, -1);
  99880. break;
  99881. }
  99882. if (_this._attachedMesh) {
  99883. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99884. }
  99885. _this.position.addToRef(_this._add, _this._target);
  99886. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99887. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99888. scene._forcedViewPosition = _this.position;
  99889. });
  99890. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99891. scene._forcedViewPosition = null;
  99892. scene.updateTransformMatrix(true);
  99893. });
  99894. if (scene.activeCamera) {
  99895. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99896. }
  99897. }
  99898. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99899. get: function () {
  99900. return this._renderTargetTexture.samples;
  99901. },
  99902. set: function (value) {
  99903. this._renderTargetTexture.samples = value;
  99904. },
  99905. enumerable: true,
  99906. configurable: true
  99907. });
  99908. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99909. get: function () {
  99910. return this._renderTargetTexture.refreshRate;
  99911. },
  99912. set: function (value) {
  99913. this._renderTargetTexture.refreshRate = value;
  99914. },
  99915. enumerable: true,
  99916. configurable: true
  99917. });
  99918. ReflectionProbe.prototype.getScene = function () {
  99919. return this._scene;
  99920. };
  99921. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99922. get: function () {
  99923. return this._renderTargetTexture;
  99924. },
  99925. enumerable: true,
  99926. configurable: true
  99927. });
  99928. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99929. get: function () {
  99930. return this._renderTargetTexture.renderList;
  99931. },
  99932. enumerable: true,
  99933. configurable: true
  99934. });
  99935. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99936. this._attachedMesh = mesh;
  99937. };
  99938. /**
  99939. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99940. *
  99941. * @param renderingGroupId The rendering group id corresponding to its index
  99942. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99943. */
  99944. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99945. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99946. };
  99947. ReflectionProbe.prototype.dispose = function () {
  99948. var index = this._scene.reflectionProbes.indexOf(this);
  99949. if (index !== -1) {
  99950. // Remove from the scene if found
  99951. this._scene.reflectionProbes.splice(index, 1);
  99952. }
  99953. if (this._renderTargetTexture) {
  99954. this._renderTargetTexture.dispose();
  99955. this._renderTargetTexture = null;
  99956. }
  99957. };
  99958. return ReflectionProbe;
  99959. }());
  99960. BABYLON.ReflectionProbe = ReflectionProbe;
  99961. })(BABYLON || (BABYLON = {}));
  99962. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99963. var BABYLON;
  99964. (function (BABYLON) {
  99965. /**
  99966. * Defines the layer scene component responsible to manage any layers
  99967. * in a given scene.
  99968. */
  99969. var LayerSceneComponent = /** @class */ (function () {
  99970. /**
  99971. * Creates a new instance of the component for the given scene
  99972. * @param scene Defines the scene to register the component in
  99973. */
  99974. function LayerSceneComponent(scene) {
  99975. /**
  99976. * The component name helpfull to identify the component in the list of scene components.
  99977. */
  99978. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99979. this.scene = scene;
  99980. this._engine = scene.getEngine();
  99981. scene.layers = new Array();
  99982. }
  99983. /**
  99984. * Registers the component in a given scene
  99985. */
  99986. LayerSceneComponent.prototype.register = function () {
  99987. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99988. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99989. };
  99990. /**
  99991. * Rebuilds the elements related to this component in case of
  99992. * context lost for instance.
  99993. */
  99994. LayerSceneComponent.prototype.rebuild = function () {
  99995. var layers = this.scene.layers;
  99996. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99997. var layer = layers_1[_i];
  99998. layer._rebuild();
  99999. }
  100000. };
  100001. /**
  100002. * Disposes the component and the associated ressources.
  100003. */
  100004. LayerSceneComponent.prototype.dispose = function () {
  100005. var layers = this.scene.layers;
  100006. while (layers.length) {
  100007. layers[0].dispose();
  100008. }
  100009. };
  100010. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  100011. var layers = this.scene.layers;
  100012. if (layers.length) {
  100013. this._engine.setDepthBuffer(false);
  100014. var cameraLayerMask = camera.layerMask;
  100015. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100016. var layer = layers_2[_i];
  100017. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  100018. layer.render();
  100019. }
  100020. }
  100021. this._engine.setDepthBuffer(true);
  100022. }
  100023. };
  100024. LayerSceneComponent.prototype._drawBackground = function (camera) {
  100025. this._draw(camera, true);
  100026. };
  100027. LayerSceneComponent.prototype._drawForeground = function (camera) {
  100028. this._draw(camera, false);
  100029. };
  100030. return LayerSceneComponent;
  100031. }());
  100032. BABYLON.LayerSceneComponent = LayerSceneComponent;
  100033. })(BABYLON || (BABYLON = {}));
  100034. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  100035. var BABYLON;
  100036. (function (BABYLON) {
  100037. var Layer = /** @class */ (function () {
  100038. function Layer(name, imgUrl, scene, isBackground, color) {
  100039. this.name = name;
  100040. this.scale = new BABYLON.Vector2(1, 1);
  100041. this.offset = new BABYLON.Vector2(0, 0);
  100042. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  100043. this.layerMask = 0x0FFFFFFF;
  100044. this._vertexBuffers = {};
  100045. // Events
  100046. /**
  100047. * An event triggered when the layer is disposed.
  100048. */
  100049. this.onDisposeObservable = new BABYLON.Observable();
  100050. /**
  100051. * An event triggered before rendering the scene
  100052. */
  100053. this.onBeforeRenderObservable = new BABYLON.Observable();
  100054. /**
  100055. * An event triggered after rendering the scene
  100056. */
  100057. this.onAfterRenderObservable = new BABYLON.Observable();
  100058. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  100059. this.isBackground = isBackground === undefined ? true : isBackground;
  100060. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  100061. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  100062. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  100063. if (!layerComponent) {
  100064. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  100065. this._scene._addComponent(layerComponent);
  100066. }
  100067. this._scene.layers.push(this);
  100068. var engine = this._scene.getEngine();
  100069. // VBO
  100070. var vertices = [];
  100071. vertices.push(1, 1);
  100072. vertices.push(-1, 1);
  100073. vertices.push(-1, -1);
  100074. vertices.push(1, -1);
  100075. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100076. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100077. this._createIndexBuffer();
  100078. // Effects
  100079. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  100080. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  100081. }
  100082. Object.defineProperty(Layer.prototype, "onDispose", {
  100083. set: function (callback) {
  100084. if (this._onDisposeObserver) {
  100085. this.onDisposeObservable.remove(this._onDisposeObserver);
  100086. }
  100087. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100088. },
  100089. enumerable: true,
  100090. configurable: true
  100091. });
  100092. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  100093. set: function (callback) {
  100094. if (this._onBeforeRenderObserver) {
  100095. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  100096. }
  100097. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  100098. },
  100099. enumerable: true,
  100100. configurable: true
  100101. });
  100102. Object.defineProperty(Layer.prototype, "onAfterRender", {
  100103. set: function (callback) {
  100104. if (this._onAfterRenderObserver) {
  100105. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100106. }
  100107. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  100108. },
  100109. enumerable: true,
  100110. configurable: true
  100111. });
  100112. Layer.prototype._createIndexBuffer = function () {
  100113. var engine = this._scene.getEngine();
  100114. // Indices
  100115. var indices = [];
  100116. indices.push(0);
  100117. indices.push(1);
  100118. indices.push(2);
  100119. indices.push(0);
  100120. indices.push(2);
  100121. indices.push(3);
  100122. this._indexBuffer = engine.createIndexBuffer(indices);
  100123. };
  100124. Layer.prototype._rebuild = function () {
  100125. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100126. if (vb) {
  100127. vb._rebuild();
  100128. }
  100129. this._createIndexBuffer();
  100130. };
  100131. Layer.prototype.render = function () {
  100132. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  100133. // Check
  100134. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  100135. return;
  100136. var engine = this._scene.getEngine();
  100137. this.onBeforeRenderObservable.notifyObservers(this);
  100138. // Render
  100139. engine.enableEffect(currentEffect);
  100140. engine.setState(false);
  100141. // Texture
  100142. currentEffect.setTexture("textureSampler", this.texture);
  100143. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  100144. // Color
  100145. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  100146. // Scale / offset
  100147. currentEffect.setVector2("offset", this.offset);
  100148. currentEffect.setVector2("scale", this.scale);
  100149. // VBOs
  100150. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100151. // Draw order
  100152. if (!this.alphaTest) {
  100153. engine.setAlphaMode(this.alphaBlendingMode);
  100154. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100155. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100156. }
  100157. else {
  100158. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100159. }
  100160. this.onAfterRenderObservable.notifyObservers(this);
  100161. };
  100162. Layer.prototype.dispose = function () {
  100163. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100164. if (vertexBuffer) {
  100165. vertexBuffer.dispose();
  100166. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100167. }
  100168. if (this._indexBuffer) {
  100169. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100170. this._indexBuffer = null;
  100171. }
  100172. if (this.texture) {
  100173. this.texture.dispose();
  100174. this.texture = null;
  100175. }
  100176. // Remove from scene
  100177. var index = this._scene.layers.indexOf(this);
  100178. this._scene.layers.splice(index, 1);
  100179. // Callback
  100180. this.onDisposeObservable.notifyObservers(this);
  100181. this.onDisposeObservable.clear();
  100182. this.onAfterRenderObservable.clear();
  100183. this.onBeforeRenderObservable.clear();
  100184. };
  100185. return Layer;
  100186. }());
  100187. BABYLON.Layer = Layer;
  100188. })(BABYLON || (BABYLON = {}));
  100189. //# sourceMappingURL=babylon.layer.js.map
  100190. var BABYLON;
  100191. (function (BABYLON) {
  100192. var TextureTools = /** @class */ (function () {
  100193. function TextureTools() {
  100194. }
  100195. /**
  100196. * Uses the GPU to create a copy texture rescaled at a given size
  100197. * @param texture Texture to copy from
  100198. * @param width Desired width
  100199. * @param height Desired height
  100200. * @return Generated texture
  100201. */
  100202. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  100203. if (useBilinearMode === void 0) { useBilinearMode = true; }
  100204. var scene = texture.getScene();
  100205. var engine = scene.getEngine();
  100206. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  100207. rtt.wrapU = texture.wrapU;
  100208. rtt.wrapV = texture.wrapV;
  100209. rtt.uOffset = texture.uOffset;
  100210. rtt.vOffset = texture.vOffset;
  100211. rtt.uScale = texture.uScale;
  100212. rtt.vScale = texture.vScale;
  100213. rtt.uAng = texture.uAng;
  100214. rtt.vAng = texture.vAng;
  100215. rtt.wAng = texture.wAng;
  100216. rtt.coordinatesIndex = texture.coordinatesIndex;
  100217. rtt.level = texture.level;
  100218. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  100219. rtt._texture.isReady = false;
  100220. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100221. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100222. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100223. passPostProcess.getEffect().executeWhenCompiled(function () {
  100224. passPostProcess.onApply = function (effect) {
  100225. effect.setTexture("textureSampler", texture);
  100226. };
  100227. var internalTexture = rtt.getInternalTexture();
  100228. if (internalTexture) {
  100229. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  100230. engine.unBindFramebuffer(internalTexture);
  100231. rtt.disposeFramebufferObjects();
  100232. passPostProcess.dispose();
  100233. internalTexture.isReady = true;
  100234. }
  100235. });
  100236. return rtt;
  100237. };
  100238. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  100239. if (!scene._environmentBRDFTexture) {
  100240. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100241. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100242. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100243. scene._environmentBRDFTexture = texture;
  100244. }
  100245. return scene._environmentBRDFTexture;
  100246. };
  100247. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  100248. return TextureTools;
  100249. }());
  100250. BABYLON.TextureTools = TextureTools;
  100251. })(BABYLON || (BABYLON = {}));
  100252. //# sourceMappingURL=babylon.textureTools.js.map
  100253. var BABYLON;
  100254. (function (BABYLON) {
  100255. var FramingBehavior = /** @class */ (function () {
  100256. function FramingBehavior() {
  100257. this._mode = FramingBehavior.FitFrustumSidesMode;
  100258. this._radiusScale = 1.0;
  100259. this._positionScale = 0.5;
  100260. this._defaultElevation = 0.3;
  100261. this._elevationReturnTime = 1500;
  100262. this._elevationReturnWaitTime = 1000;
  100263. this._zoomStopsAnimation = false;
  100264. this._framingTime = 1500;
  100265. this._isPointerDown = false;
  100266. this._lastInteractionTime = -Infinity;
  100267. // Framing control
  100268. this._animatables = new Array();
  100269. this._betaIsAnimating = false;
  100270. }
  100271. Object.defineProperty(FramingBehavior.prototype, "name", {
  100272. get: function () {
  100273. return "Framing";
  100274. },
  100275. enumerable: true,
  100276. configurable: true
  100277. });
  100278. Object.defineProperty(FramingBehavior.prototype, "mode", {
  100279. /**
  100280. * Gets current mode used by the behavior.
  100281. */
  100282. get: function () {
  100283. return this._mode;
  100284. },
  100285. /**
  100286. * Sets the current mode used by the behavior
  100287. */
  100288. set: function (mode) {
  100289. this._mode = mode;
  100290. },
  100291. enumerable: true,
  100292. configurable: true
  100293. });
  100294. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  100295. /**
  100296. * Gets the scale applied to the radius
  100297. */
  100298. get: function () {
  100299. return this._radiusScale;
  100300. },
  100301. /**
  100302. * Sets the scale applied to the radius (1 by default)
  100303. */
  100304. set: function (radius) {
  100305. this._radiusScale = radius;
  100306. },
  100307. enumerable: true,
  100308. configurable: true
  100309. });
  100310. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  100311. /**
  100312. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100313. */
  100314. get: function () {
  100315. return this._positionScale;
  100316. },
  100317. /**
  100318. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100319. */
  100320. set: function (scale) {
  100321. this._positionScale = scale;
  100322. },
  100323. enumerable: true,
  100324. configurable: true
  100325. });
  100326. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  100327. /**
  100328. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100329. * behaviour is triggered, in radians.
  100330. */
  100331. get: function () {
  100332. return this._defaultElevation;
  100333. },
  100334. /**
  100335. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100336. * behaviour is triggered, in radians.
  100337. */
  100338. set: function (elevation) {
  100339. this._defaultElevation = elevation;
  100340. },
  100341. enumerable: true,
  100342. configurable: true
  100343. });
  100344. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  100345. /**
  100346. * Gets the time (in milliseconds) taken to return to the default beta position.
  100347. * Negative value indicates camera should not return to default.
  100348. */
  100349. get: function () {
  100350. return this._elevationReturnTime;
  100351. },
  100352. /**
  100353. * Sets the time (in milliseconds) taken to return to the default beta position.
  100354. * Negative value indicates camera should not return to default.
  100355. */
  100356. set: function (speed) {
  100357. this._elevationReturnTime = speed;
  100358. },
  100359. enumerable: true,
  100360. configurable: true
  100361. });
  100362. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  100363. /**
  100364. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100365. */
  100366. get: function () {
  100367. return this._elevationReturnWaitTime;
  100368. },
  100369. /**
  100370. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100371. */
  100372. set: function (time) {
  100373. this._elevationReturnWaitTime = time;
  100374. },
  100375. enumerable: true,
  100376. configurable: true
  100377. });
  100378. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  100379. /**
  100380. * Gets the flag that indicates if user zooming should stop animation.
  100381. */
  100382. get: function () {
  100383. return this._zoomStopsAnimation;
  100384. },
  100385. /**
  100386. * Sets the flag that indicates if user zooming should stop animation.
  100387. */
  100388. set: function (flag) {
  100389. this._zoomStopsAnimation = flag;
  100390. },
  100391. enumerable: true,
  100392. configurable: true
  100393. });
  100394. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  100395. /**
  100396. * Gets the transition time when framing the mesh, in milliseconds
  100397. */
  100398. get: function () {
  100399. return this._framingTime;
  100400. },
  100401. /**
  100402. * Sets the transition time when framing the mesh, in milliseconds
  100403. */
  100404. set: function (time) {
  100405. this._framingTime = time;
  100406. },
  100407. enumerable: true,
  100408. configurable: true
  100409. });
  100410. FramingBehavior.prototype.init = function () {
  100411. // Do notihng
  100412. };
  100413. FramingBehavior.prototype.attach = function (camera) {
  100414. var _this = this;
  100415. this._attachedCamera = camera;
  100416. var scene = this._attachedCamera.getScene();
  100417. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  100418. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100419. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100420. _this._isPointerDown = true;
  100421. return;
  100422. }
  100423. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100424. _this._isPointerDown = false;
  100425. }
  100426. });
  100427. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100428. if (mesh) {
  100429. _this.zoomOnMesh(mesh);
  100430. }
  100431. });
  100432. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100433. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100434. _this._applyUserInteraction();
  100435. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  100436. // back to the default position after a given timeout
  100437. _this._maintainCameraAboveGround();
  100438. });
  100439. };
  100440. FramingBehavior.prototype.detach = function () {
  100441. if (!this._attachedCamera) {
  100442. return;
  100443. }
  100444. var scene = this._attachedCamera.getScene();
  100445. if (this._onPrePointerObservableObserver) {
  100446. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100447. }
  100448. if (this._onAfterCheckInputsObserver) {
  100449. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100450. }
  100451. if (this._onMeshTargetChangedObserver) {
  100452. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100453. }
  100454. this._attachedCamera = null;
  100455. };
  100456. /**
  100457. * Targets the given mesh and updates zoom level accordingly.
  100458. * @param mesh The mesh to target.
  100459. * @param radius Optional. If a cached radius position already exists, overrides default.
  100460. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100461. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100462. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100463. */
  100464. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100465. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100466. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100467. mesh.computeWorldMatrix(true);
  100468. var boundingBox = mesh.getBoundingInfo().boundingBox;
  100469. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  100470. };
  100471. /**
  100472. * Targets the given mesh with its children and updates zoom level accordingly.
  100473. * @param mesh The mesh to target.
  100474. * @param radius Optional. If a cached radius position already exists, overrides default.
  100475. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100476. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100477. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100478. */
  100479. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100480. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100481. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100482. mesh.computeWorldMatrix(true);
  100483. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  100484. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  100485. };
  100486. /**
  100487. * Targets the given meshes with their children and updates zoom level accordingly.
  100488. * @param meshes The mesh to target.
  100489. * @param radius Optional. If a cached radius position already exists, overrides default.
  100490. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100491. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100492. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100493. */
  100494. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  100495. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100496. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100497. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  100498. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  100499. for (var i = 0; i < meshes.length; i++) {
  100500. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  100501. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  100502. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  100503. }
  100504. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  100505. };
  100506. /**
  100507. * Targets the given mesh and updates zoom level accordingly.
  100508. * @param mesh The mesh to target.
  100509. * @param radius Optional. If a cached radius position already exists, overrides default.
  100510. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100511. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100512. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100513. */
  100514. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  100515. var _this = this;
  100516. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100517. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100518. var zoomTarget;
  100519. if (!this._attachedCamera) {
  100520. return;
  100521. }
  100522. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  100523. var bottom = minimumWorld.y;
  100524. var top = maximumWorld.y;
  100525. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  100526. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  100527. if (focusOnOriginXZ) {
  100528. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  100529. }
  100530. else {
  100531. var centerWorld = minimumWorld.add(radiusWorld);
  100532. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  100533. }
  100534. if (!this._vectorTransition) {
  100535. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  100536. }
  100537. this._betaIsAnimating = true;
  100538. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  100539. if (animatable) {
  100540. this._animatables.push(animatable);
  100541. }
  100542. // sets the radius and lower radius bounds
  100543. // Small delta ensures camera is not always at lower zoom limit.
  100544. var radius = 0;
  100545. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  100546. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100547. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  100548. radius = position;
  100549. }
  100550. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100551. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100552. if (this._attachedCamera.lowerRadiusLimit === null) {
  100553. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  100554. }
  100555. }
  100556. // Set sensibilities
  100557. var extend = maximumWorld.subtract(minimumWorld).length();
  100558. this._attachedCamera.panningSensibility = 5000 / extend;
  100559. this._attachedCamera.wheelPrecision = 100 / radius;
  100560. // transition to new radius
  100561. if (!this._radiusTransition) {
  100562. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100563. }
  100564. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  100565. _this.stopAllAnimations();
  100566. if (onAnimationEnd) {
  100567. onAnimationEnd();
  100568. }
  100569. if (_this._attachedCamera) {
  100570. _this._attachedCamera.storeState();
  100571. }
  100572. });
  100573. if (animatable) {
  100574. this._animatables.push(animatable);
  100575. }
  100576. };
  100577. /**
  100578. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  100579. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  100580. * frustum width.
  100581. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  100582. * to fully enclose the mesh in the viewing frustum.
  100583. */
  100584. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  100585. var size = maximumWorld.subtract(minimumWorld);
  100586. var boxVectorGlobalDiagonal = size.length();
  100587. var frustumSlope = this._getFrustumSlope();
  100588. // Formula for setting distance
  100589. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  100590. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  100591. // Horizon distance
  100592. var radius = radiusWithoutFraming * this._radiusScale;
  100593. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  100594. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  100595. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  100596. var camera = this._attachedCamera;
  100597. if (!camera) {
  100598. return 0;
  100599. }
  100600. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100601. // Don't exceed the requested limit
  100602. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  100603. }
  100604. // Don't exceed the upper radius limit
  100605. if (camera.upperRadiusLimit) {
  100606. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  100607. }
  100608. return distance;
  100609. };
  100610. /**
  100611. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  100612. * is automatically returned to its default position (expected to be above ground plane).
  100613. */
  100614. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  100615. var _this = this;
  100616. if (this._elevationReturnTime < 0) {
  100617. return;
  100618. }
  100619. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  100620. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  100621. var limitBeta = Math.PI * 0.5;
  100622. // Bring the camera back up if below the ground plane
  100623. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  100624. this._betaIsAnimating = true;
  100625. //Transition to new position
  100626. this.stopAllAnimations();
  100627. if (!this._betaTransition) {
  100628. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100629. }
  100630. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  100631. _this._clearAnimationLocks();
  100632. _this.stopAllAnimations();
  100633. });
  100634. if (animatabe) {
  100635. this._animatables.push(animatabe);
  100636. }
  100637. }
  100638. };
  100639. /**
  100640. * Returns the frustum slope based on the canvas ratio and camera FOV
  100641. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  100642. */
  100643. FramingBehavior.prototype._getFrustumSlope = function () {
  100644. // Calculate the viewport ratio
  100645. // Aspect Ratio is Height/Width.
  100646. var camera = this._attachedCamera;
  100647. if (!camera) {
  100648. return BABYLON.Vector2.Zero();
  100649. }
  100650. var engine = camera.getScene().getEngine();
  100651. var aspectRatio = engine.getAspectRatio(camera);
  100652. // Camera FOV is the vertical field of view (top-bottom) in radians.
  100653. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  100654. var frustumSlopeY = Math.tan(camera.fov / 2);
  100655. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  100656. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  100657. // along the forward vector.
  100658. var frustumSlopeX = frustumSlopeY * aspectRatio;
  100659. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  100660. };
  100661. /**
  100662. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  100663. */
  100664. FramingBehavior.prototype._clearAnimationLocks = function () {
  100665. this._betaIsAnimating = false;
  100666. };
  100667. /**
  100668. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100669. */
  100670. FramingBehavior.prototype._applyUserInteraction = function () {
  100671. if (this.isUserIsMoving) {
  100672. this._lastInteractionTime = BABYLON.Tools.Now;
  100673. this.stopAllAnimations();
  100674. this._clearAnimationLocks();
  100675. }
  100676. };
  100677. /**
  100678. * Stops and removes all animations that have been applied to the camera
  100679. */
  100680. FramingBehavior.prototype.stopAllAnimations = function () {
  100681. if (this._attachedCamera) {
  100682. this._attachedCamera.animations = [];
  100683. }
  100684. while (this._animatables.length) {
  100685. if (this._animatables[0]) {
  100686. this._animatables[0].onAnimationEnd = null;
  100687. this._animatables[0].stop();
  100688. }
  100689. this._animatables.shift();
  100690. }
  100691. };
  100692. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  100693. /**
  100694. * Gets a value indicating if the user is moving the camera
  100695. */
  100696. get: function () {
  100697. if (!this._attachedCamera) {
  100698. return false;
  100699. }
  100700. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100701. this._attachedCamera.inertialBetaOffset !== 0 ||
  100702. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100703. this._attachedCamera.inertialPanningX !== 0 ||
  100704. this._attachedCamera.inertialPanningY !== 0 ||
  100705. this._isPointerDown;
  100706. },
  100707. enumerable: true,
  100708. configurable: true
  100709. });
  100710. /**
  100711. * The easing function used by animations
  100712. */
  100713. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  100714. /**
  100715. * The easing mode used by animations
  100716. */
  100717. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  100718. // Statics
  100719. /**
  100720. * The camera can move all the way towards the mesh.
  100721. */
  100722. FramingBehavior.IgnoreBoundsSizeMode = 0;
  100723. /**
  100724. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  100725. */
  100726. FramingBehavior.FitFrustumSidesMode = 1;
  100727. return FramingBehavior;
  100728. }());
  100729. BABYLON.FramingBehavior = FramingBehavior;
  100730. })(BABYLON || (BABYLON = {}));
  100731. //# sourceMappingURL=babylon.framingBehavior.js.map
  100732. var BABYLON;
  100733. (function (BABYLON) {
  100734. /**
  100735. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  100736. */
  100737. var BouncingBehavior = /** @class */ (function () {
  100738. function BouncingBehavior() {
  100739. /**
  100740. * The duration of the animation, in milliseconds
  100741. */
  100742. this.transitionDuration = 450;
  100743. /**
  100744. * Length of the distance animated by the transition when lower radius is reached
  100745. */
  100746. this.lowerRadiusTransitionRange = 2;
  100747. /**
  100748. * Length of the distance animated by the transition when upper radius is reached
  100749. */
  100750. this.upperRadiusTransitionRange = -2;
  100751. this._autoTransitionRange = false;
  100752. // Animations
  100753. this._radiusIsAnimating = false;
  100754. this._radiusBounceTransition = null;
  100755. this._animatables = new Array();
  100756. }
  100757. Object.defineProperty(BouncingBehavior.prototype, "name", {
  100758. get: function () {
  100759. return "Bouncing";
  100760. },
  100761. enumerable: true,
  100762. configurable: true
  100763. });
  100764. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  100765. /**
  100766. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100767. */
  100768. get: function () {
  100769. return this._autoTransitionRange;
  100770. },
  100771. /**
  100772. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100773. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  100774. */
  100775. set: function (value) {
  100776. var _this = this;
  100777. if (this._autoTransitionRange === value) {
  100778. return;
  100779. }
  100780. this._autoTransitionRange = value;
  100781. var camera = this._attachedCamera;
  100782. if (!camera) {
  100783. return;
  100784. }
  100785. if (value) {
  100786. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100787. if (!mesh) {
  100788. return;
  100789. }
  100790. mesh.computeWorldMatrix(true);
  100791. var diagonal = mesh.getBoundingInfo().diagonalLength;
  100792. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  100793. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100794. });
  100795. }
  100796. else if (this._onMeshTargetChangedObserver) {
  100797. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100798. }
  100799. },
  100800. enumerable: true,
  100801. configurable: true
  100802. });
  100803. BouncingBehavior.prototype.init = function () {
  100804. // Do notihng
  100805. };
  100806. BouncingBehavior.prototype.attach = function (camera) {
  100807. var _this = this;
  100808. this._attachedCamera = camera;
  100809. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100810. if (!_this._attachedCamera) {
  100811. return;
  100812. }
  100813. // Add the bounce animation to the lower radius limit
  100814. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100815. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100816. }
  100817. // Add the bounce animation to the upper radius limit
  100818. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100819. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100820. }
  100821. });
  100822. };
  100823. BouncingBehavior.prototype.detach = function () {
  100824. if (!this._attachedCamera) {
  100825. return;
  100826. }
  100827. if (this._onAfterCheckInputsObserver) {
  100828. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100829. }
  100830. if (this._onMeshTargetChangedObserver) {
  100831. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100832. }
  100833. this._attachedCamera = null;
  100834. };
  100835. /**
  100836. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100837. * @param radiusLimit The limit to check against.
  100838. * @return Bool to indicate if at limit.
  100839. */
  100840. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100841. if (!this._attachedCamera) {
  100842. return false;
  100843. }
  100844. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100845. return true;
  100846. }
  100847. return false;
  100848. };
  100849. /**
  100850. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100851. * @param radiusDelta The delta by which to animate to. Can be negative.
  100852. */
  100853. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100854. var _this = this;
  100855. if (!this._attachedCamera) {
  100856. return;
  100857. }
  100858. if (!this._radiusBounceTransition) {
  100859. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100860. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100861. }
  100862. // Prevent zoom until bounce has completed
  100863. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100864. this._attachedCamera.wheelPrecision = Infinity;
  100865. this._attachedCamera.inertialRadiusOffset = 0;
  100866. // Animate to the radius limit
  100867. this.stopAllAnimations();
  100868. this._radiusIsAnimating = true;
  100869. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100870. if (animatable) {
  100871. this._animatables.push(animatable);
  100872. }
  100873. };
  100874. /**
  100875. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100876. */
  100877. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100878. this._radiusIsAnimating = false;
  100879. if (this._attachedCamera) {
  100880. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100881. }
  100882. };
  100883. /**
  100884. * Stops and removes all animations that have been applied to the camera
  100885. */
  100886. BouncingBehavior.prototype.stopAllAnimations = function () {
  100887. if (this._attachedCamera) {
  100888. this._attachedCamera.animations = [];
  100889. }
  100890. while (this._animatables.length) {
  100891. this._animatables[0].onAnimationEnd = null;
  100892. this._animatables[0].stop();
  100893. this._animatables.shift();
  100894. }
  100895. };
  100896. /**
  100897. * The easing function used by animations
  100898. */
  100899. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100900. /**
  100901. * The easing mode used by animations
  100902. */
  100903. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100904. return BouncingBehavior;
  100905. }());
  100906. BABYLON.BouncingBehavior = BouncingBehavior;
  100907. })(BABYLON || (BABYLON = {}));
  100908. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100909. var BABYLON;
  100910. (function (BABYLON) {
  100911. var AutoRotationBehavior = /** @class */ (function () {
  100912. function AutoRotationBehavior() {
  100913. this._zoomStopsAnimation = false;
  100914. this._idleRotationSpeed = 0.05;
  100915. this._idleRotationWaitTime = 2000;
  100916. this._idleRotationSpinupTime = 2000;
  100917. this._isPointerDown = false;
  100918. this._lastFrameTime = null;
  100919. this._lastInteractionTime = -Infinity;
  100920. this._cameraRotationSpeed = 0;
  100921. this._lastFrameRadius = 0;
  100922. }
  100923. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100924. get: function () {
  100925. return "AutoRotation";
  100926. },
  100927. enumerable: true,
  100928. configurable: true
  100929. });
  100930. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100931. /**
  100932. * Gets the flag that indicates if user zooming should stop animation.
  100933. */
  100934. get: function () {
  100935. return this._zoomStopsAnimation;
  100936. },
  100937. /**
  100938. * Sets the flag that indicates if user zooming should stop animation.
  100939. */
  100940. set: function (flag) {
  100941. this._zoomStopsAnimation = flag;
  100942. },
  100943. enumerable: true,
  100944. configurable: true
  100945. });
  100946. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100947. /**
  100948. * Gets the default speed at which the camera rotates around the model.
  100949. */
  100950. get: function () {
  100951. return this._idleRotationSpeed;
  100952. },
  100953. /**
  100954. * Sets the default speed at which the camera rotates around the model.
  100955. */
  100956. set: function (speed) {
  100957. this._idleRotationSpeed = speed;
  100958. },
  100959. enumerable: true,
  100960. configurable: true
  100961. });
  100962. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100963. /**
  100964. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100965. */
  100966. get: function () {
  100967. return this._idleRotationWaitTime;
  100968. },
  100969. /**
  100970. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100971. */
  100972. set: function (time) {
  100973. this._idleRotationWaitTime = time;
  100974. },
  100975. enumerable: true,
  100976. configurable: true
  100977. });
  100978. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100979. /**
  100980. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100981. */
  100982. get: function () {
  100983. return this._idleRotationSpinupTime;
  100984. },
  100985. /**
  100986. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100987. */
  100988. set: function (time) {
  100989. this._idleRotationSpinupTime = time;
  100990. },
  100991. enumerable: true,
  100992. configurable: true
  100993. });
  100994. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100995. /**
  100996. * Gets a value indicating if the camera is currently rotating because of this behavior
  100997. */
  100998. get: function () {
  100999. return Math.abs(this._cameraRotationSpeed) > 0;
  101000. },
  101001. enumerable: true,
  101002. configurable: true
  101003. });
  101004. AutoRotationBehavior.prototype.init = function () {
  101005. // Do notihng
  101006. };
  101007. AutoRotationBehavior.prototype.attach = function (camera) {
  101008. var _this = this;
  101009. this._attachedCamera = camera;
  101010. var scene = this._attachedCamera.getScene();
  101011. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101012. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101013. _this._isPointerDown = true;
  101014. return;
  101015. }
  101016. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101017. _this._isPointerDown = false;
  101018. }
  101019. });
  101020. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101021. var now = BABYLON.Tools.Now;
  101022. var dt = 0;
  101023. if (_this._lastFrameTime != null) {
  101024. dt = now - _this._lastFrameTime;
  101025. }
  101026. _this._lastFrameTime = now;
  101027. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101028. _this._applyUserInteraction();
  101029. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  101030. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  101031. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  101032. // Step camera rotation by rotation speed
  101033. if (_this._attachedCamera) {
  101034. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  101035. }
  101036. });
  101037. };
  101038. AutoRotationBehavior.prototype.detach = function () {
  101039. if (!this._attachedCamera) {
  101040. return;
  101041. }
  101042. var scene = this._attachedCamera.getScene();
  101043. if (this._onPrePointerObservableObserver) {
  101044. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101045. }
  101046. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101047. this._attachedCamera = null;
  101048. };
  101049. /**
  101050. * Returns true if user is scrolling.
  101051. * @return true if user is scrolling.
  101052. */
  101053. AutoRotationBehavior.prototype._userIsZooming = function () {
  101054. if (!this._attachedCamera) {
  101055. return false;
  101056. }
  101057. return this._attachedCamera.inertialRadiusOffset !== 0;
  101058. };
  101059. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  101060. if (!this._attachedCamera) {
  101061. return false;
  101062. }
  101063. var zoomHasHitLimit = false;
  101064. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  101065. zoomHasHitLimit = true;
  101066. }
  101067. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  101068. this._lastFrameRadius = this._attachedCamera.radius;
  101069. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  101070. };
  101071. /**
  101072. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101073. */
  101074. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  101075. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  101076. this._lastInteractionTime = BABYLON.Tools.Now;
  101077. }
  101078. };
  101079. // Tools
  101080. AutoRotationBehavior.prototype._userIsMoving = function () {
  101081. if (!this._attachedCamera) {
  101082. return false;
  101083. }
  101084. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101085. this._attachedCamera.inertialBetaOffset !== 0 ||
  101086. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101087. this._attachedCamera.inertialPanningX !== 0 ||
  101088. this._attachedCamera.inertialPanningY !== 0 ||
  101089. this._isPointerDown;
  101090. };
  101091. return AutoRotationBehavior;
  101092. }());
  101093. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  101094. })(BABYLON || (BABYLON = {}));
  101095. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  101096. var BABYLON;
  101097. (function (BABYLON) {
  101098. var NullEngineOptions = /** @class */ (function () {
  101099. function NullEngineOptions() {
  101100. this.renderWidth = 512;
  101101. this.renderHeight = 256;
  101102. this.textureSize = 512;
  101103. this.deterministicLockstep = false;
  101104. this.lockstepMaxSteps = 4;
  101105. }
  101106. return NullEngineOptions;
  101107. }());
  101108. BABYLON.NullEngineOptions = NullEngineOptions;
  101109. /**
  101110. * The null engine class provides support for headless version of babylon.js.
  101111. * This can be used in server side scenario or for testing purposes
  101112. */
  101113. var NullEngine = /** @class */ (function (_super) {
  101114. __extends(NullEngine, _super);
  101115. function NullEngine(options) {
  101116. if (options === void 0) { options = new NullEngineOptions(); }
  101117. var _this = _super.call(this, null) || this;
  101118. if (options.deterministicLockstep === undefined) {
  101119. options.deterministicLockstep = false;
  101120. }
  101121. if (options.lockstepMaxSteps === undefined) {
  101122. options.lockstepMaxSteps = 4;
  101123. }
  101124. _this._options = options;
  101125. // Init caps
  101126. // We consider we are on a webgl1 capable device
  101127. _this._caps = new BABYLON.EngineCapabilities();
  101128. _this._caps.maxTexturesImageUnits = 16;
  101129. _this._caps.maxVertexTextureImageUnits = 16;
  101130. _this._caps.maxTextureSize = 512;
  101131. _this._caps.maxCubemapTextureSize = 512;
  101132. _this._caps.maxRenderTextureSize = 512;
  101133. _this._caps.maxVertexAttribs = 16;
  101134. _this._caps.maxVaryingVectors = 16;
  101135. _this._caps.maxFragmentUniformVectors = 16;
  101136. _this._caps.maxVertexUniformVectors = 16;
  101137. // Extensions
  101138. _this._caps.standardDerivatives = false;
  101139. _this._caps.astc = null;
  101140. _this._caps.s3tc = null;
  101141. _this._caps.pvrtc = null;
  101142. _this._caps.etc1 = null;
  101143. _this._caps.etc2 = null;
  101144. _this._caps.textureAnisotropicFilterExtension = null;
  101145. _this._caps.maxAnisotropy = 0;
  101146. _this._caps.uintIndices = false;
  101147. _this._caps.fragmentDepthSupported = false;
  101148. _this._caps.highPrecisionShaderSupported = true;
  101149. _this._caps.colorBufferFloat = false;
  101150. _this._caps.textureFloat = false;
  101151. _this._caps.textureFloatLinearFiltering = false;
  101152. _this._caps.textureFloatRender = false;
  101153. _this._caps.textureHalfFloat = false;
  101154. _this._caps.textureHalfFloatLinearFiltering = false;
  101155. _this._caps.textureHalfFloatRender = false;
  101156. _this._caps.textureLOD = false;
  101157. _this._caps.drawBuffersExtension = false;
  101158. _this._caps.depthTextureExtension = false;
  101159. _this._caps.vertexArrayObject = false;
  101160. _this._caps.instancedArrays = false;
  101161. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  101162. // Wrappers
  101163. if (typeof URL === "undefined") {
  101164. URL = {
  101165. createObjectURL: function () { },
  101166. revokeObjectURL: function () { }
  101167. };
  101168. }
  101169. if (typeof Blob === "undefined") {
  101170. Blob = function () { };
  101171. }
  101172. return _this;
  101173. }
  101174. NullEngine.prototype.isDeterministicLockStep = function () {
  101175. return this._options.deterministicLockstep;
  101176. };
  101177. NullEngine.prototype.getLockstepMaxSteps = function () {
  101178. return this._options.lockstepMaxSteps;
  101179. };
  101180. NullEngine.prototype.getHardwareScalingLevel = function () {
  101181. return 1.0;
  101182. };
  101183. NullEngine.prototype.createVertexBuffer = function (vertices) {
  101184. return {
  101185. capacity: 0,
  101186. references: 1,
  101187. is32Bits: false
  101188. };
  101189. };
  101190. NullEngine.prototype.createIndexBuffer = function (indices) {
  101191. return {
  101192. capacity: 0,
  101193. references: 1,
  101194. is32Bits: false
  101195. };
  101196. };
  101197. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  101198. if (stencil === void 0) { stencil = false; }
  101199. };
  101200. NullEngine.prototype.getRenderWidth = function (useScreen) {
  101201. if (useScreen === void 0) { useScreen = false; }
  101202. if (!useScreen && this._currentRenderTarget) {
  101203. return this._currentRenderTarget.width;
  101204. }
  101205. return this._options.renderWidth;
  101206. };
  101207. NullEngine.prototype.getRenderHeight = function (useScreen) {
  101208. if (useScreen === void 0) { useScreen = false; }
  101209. if (!useScreen && this._currentRenderTarget) {
  101210. return this._currentRenderTarget.height;
  101211. }
  101212. return this._options.renderHeight;
  101213. };
  101214. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  101215. this._cachedViewport = viewport;
  101216. };
  101217. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  101218. return {
  101219. transformFeedback: null,
  101220. __SPECTOR_rebuildProgram: null
  101221. };
  101222. };
  101223. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  101224. return [];
  101225. };
  101226. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  101227. return [];
  101228. };
  101229. NullEngine.prototype.bindSamplers = function (effect) {
  101230. this._currentEffect = null;
  101231. };
  101232. NullEngine.prototype.enableEffect = function (effect) {
  101233. this._currentEffect = effect;
  101234. if (effect.onBind) {
  101235. effect.onBind(effect);
  101236. }
  101237. effect.onBindObservable.notifyObservers(effect);
  101238. };
  101239. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  101240. if (zOffset === void 0) { zOffset = 0; }
  101241. if (reverseSide === void 0) { reverseSide = false; }
  101242. };
  101243. NullEngine.prototype.setIntArray = function (uniform, array) {
  101244. };
  101245. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  101246. };
  101247. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  101248. };
  101249. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  101250. };
  101251. NullEngine.prototype.setFloatArray = function (uniform, array) {
  101252. };
  101253. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  101254. };
  101255. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  101256. };
  101257. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  101258. };
  101259. NullEngine.prototype.setArray = function (uniform, array) {
  101260. };
  101261. NullEngine.prototype.setArray2 = function (uniform, array) {
  101262. };
  101263. NullEngine.prototype.setArray3 = function (uniform, array) {
  101264. };
  101265. NullEngine.prototype.setArray4 = function (uniform, array) {
  101266. };
  101267. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  101268. };
  101269. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  101270. };
  101271. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  101272. };
  101273. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  101274. };
  101275. NullEngine.prototype.setFloat = function (uniform, value) {
  101276. };
  101277. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  101278. };
  101279. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  101280. };
  101281. NullEngine.prototype.setBool = function (uniform, bool) {
  101282. };
  101283. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  101284. };
  101285. NullEngine.prototype.setColor3 = function (uniform, color3) {
  101286. };
  101287. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  101288. };
  101289. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  101290. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  101291. if (this._alphaMode === mode) {
  101292. return;
  101293. }
  101294. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  101295. if (!noDepthWriteChange) {
  101296. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  101297. }
  101298. this._alphaMode = mode;
  101299. };
  101300. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  101301. };
  101302. NullEngine.prototype.wipeCaches = function (bruteForce) {
  101303. if (this.preventCacheWipeBetweenFrames) {
  101304. return;
  101305. }
  101306. this.resetTextureCache();
  101307. this._currentEffect = null;
  101308. if (bruteForce) {
  101309. this._currentProgram = null;
  101310. this._stencilState.reset();
  101311. this._depthCullingState.reset();
  101312. this._alphaState.reset();
  101313. }
  101314. this._cachedVertexBuffers = null;
  101315. this._cachedIndexBuffer = null;
  101316. this._cachedEffectForVertexBuffers = null;
  101317. };
  101318. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  101319. };
  101320. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  101321. };
  101322. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  101323. };
  101324. NullEngine.prototype._createTexture = function () {
  101325. return {};
  101326. };
  101327. NullEngine.prototype._releaseTexture = function (texture) {
  101328. };
  101329. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  101330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101331. if (onLoad === void 0) { onLoad = null; }
  101332. if (onError === void 0) { onError = null; }
  101333. if (buffer === void 0) { buffer = null; }
  101334. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  101335. var url = String(urlArg);
  101336. texture.url = url;
  101337. texture.generateMipMaps = !noMipmap;
  101338. texture.samplingMode = samplingMode;
  101339. texture.invertY = invertY;
  101340. texture.baseWidth = this._options.textureSize;
  101341. texture.baseHeight = this._options.textureSize;
  101342. texture.width = this._options.textureSize;
  101343. texture.height = this._options.textureSize;
  101344. if (format) {
  101345. texture.format = format;
  101346. }
  101347. texture.isReady = true;
  101348. if (onLoad) {
  101349. onLoad();
  101350. }
  101351. this._internalTexturesCache.push(texture);
  101352. return texture;
  101353. };
  101354. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  101355. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  101356. if (options !== undefined && typeof options === "object") {
  101357. fullOptions.generateMipMaps = options.generateMipMaps;
  101358. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  101359. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  101360. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  101361. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  101362. }
  101363. else {
  101364. fullOptions.generateMipMaps = options;
  101365. fullOptions.generateDepthBuffer = true;
  101366. fullOptions.generateStencilBuffer = false;
  101367. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101368. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  101369. }
  101370. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  101371. var width = size.width || size;
  101372. var height = size.height || size;
  101373. texture._depthStencilBuffer = {};
  101374. texture._framebuffer = {};
  101375. texture.baseWidth = width;
  101376. texture.baseHeight = height;
  101377. texture.width = width;
  101378. texture.height = height;
  101379. texture.isReady = true;
  101380. texture.samples = 1;
  101381. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  101382. texture.samplingMode = fullOptions.samplingMode;
  101383. texture.type = fullOptions.type;
  101384. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  101385. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  101386. this._internalTexturesCache.push(texture);
  101387. return texture;
  101388. };
  101389. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  101390. texture.samplingMode = samplingMode;
  101391. };
  101392. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  101393. if (this._currentRenderTarget) {
  101394. this.unBindFramebuffer(this._currentRenderTarget);
  101395. }
  101396. this._currentRenderTarget = texture;
  101397. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  101398. if (this._cachedViewport && !forceFullscreenViewport) {
  101399. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  101400. }
  101401. };
  101402. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  101403. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  101404. this._currentRenderTarget = null;
  101405. if (onBeforeUnbind) {
  101406. if (texture._MSAAFramebuffer) {
  101407. this._currentFramebuffer = texture._framebuffer;
  101408. }
  101409. onBeforeUnbind();
  101410. }
  101411. this._currentFramebuffer = null;
  101412. };
  101413. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  101414. var vbo = {
  101415. capacity: 1,
  101416. references: 1,
  101417. is32Bits: false
  101418. };
  101419. return vbo;
  101420. };
  101421. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  101422. if (premulAlpha === void 0) { premulAlpha = false; }
  101423. };
  101424. /**
  101425. * Get the current error code of the webGL context
  101426. * @returns the error code
  101427. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  101428. */
  101429. NullEngine.prototype.getError = function () {
  101430. return 0;
  101431. };
  101432. /** @hidden */
  101433. NullEngine.prototype._getUnpackAlignement = function () {
  101434. return 1;
  101435. };
  101436. /** @hidden */
  101437. NullEngine.prototype._unpackFlipY = function (value) {
  101438. };
  101439. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  101440. if (offset === void 0) { offset = 0; }
  101441. };
  101442. /**
  101443. * Updates a dynamic vertex buffer.
  101444. * @param vertexBuffer the vertex buffer to update
  101445. * @param data the data used to update the vertex buffer
  101446. * @param byteOffset the byte offset of the data (optional)
  101447. * @param byteLength the byte length of the data (optional)
  101448. */
  101449. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  101450. };
  101451. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  101452. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  101453. this._boundTexturesCache[this._activeChannel] = texture;
  101454. return true;
  101455. }
  101456. return false;
  101457. };
  101458. NullEngine.prototype._bindTexture = function (channel, texture) {
  101459. if (channel < 0) {
  101460. return;
  101461. }
  101462. this._bindTextureDirectly(0, texture);
  101463. };
  101464. NullEngine.prototype._releaseBuffer = function (buffer) {
  101465. buffer.references--;
  101466. if (buffer.references === 0) {
  101467. return true;
  101468. }
  101469. return false;
  101470. };
  101471. NullEngine.prototype.releaseEffects = function () {
  101472. };
  101473. NullEngine.prototype.displayLoadingUI = function () {
  101474. };
  101475. NullEngine.prototype.hideLoadingUI = function () {
  101476. };
  101477. /** @hidden */
  101478. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  101479. if (faceIndex === void 0) { faceIndex = 0; }
  101480. if (lod === void 0) { lod = 0; }
  101481. };
  101482. /** @hidden */
  101483. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  101484. if (faceIndex === void 0) { faceIndex = 0; }
  101485. if (lod === void 0) { lod = 0; }
  101486. };
  101487. /** @hidden */
  101488. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  101489. if (faceIndex === void 0) { faceIndex = 0; }
  101490. if (lod === void 0) { lod = 0; }
  101491. };
  101492. /** @hidden */
  101493. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  101494. if (faceIndex === void 0) { faceIndex = 0; }
  101495. if (lod === void 0) { lod = 0; }
  101496. };
  101497. return NullEngine;
  101498. }(BABYLON.Engine));
  101499. BABYLON.NullEngine = NullEngine;
  101500. })(BABYLON || (BABYLON = {}));
  101501. //# sourceMappingURL=babylon.nullEngine.js.map
  101502. var BABYLON;
  101503. (function (BABYLON) {
  101504. /**
  101505. * This class can be used to get instrumentation data from a Babylon engine
  101506. */
  101507. var EngineInstrumentation = /** @class */ (function () {
  101508. function EngineInstrumentation(engine) {
  101509. this.engine = engine;
  101510. this._captureGPUFrameTime = false;
  101511. this._gpuFrameTime = new BABYLON.PerfCounter();
  101512. this._captureShaderCompilationTime = false;
  101513. this._shaderCompilationTime = new BABYLON.PerfCounter();
  101514. // Observers
  101515. this._onBeginFrameObserver = null;
  101516. this._onEndFrameObserver = null;
  101517. this._onBeforeShaderCompilationObserver = null;
  101518. this._onAfterShaderCompilationObserver = null;
  101519. }
  101520. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  101521. // Properties
  101522. /**
  101523. * Gets the perf counter used for GPU frame time
  101524. */
  101525. get: function () {
  101526. return this._gpuFrameTime;
  101527. },
  101528. enumerable: true,
  101529. configurable: true
  101530. });
  101531. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  101532. /**
  101533. * Gets the GPU frame time capture status
  101534. */
  101535. get: function () {
  101536. return this._captureGPUFrameTime;
  101537. },
  101538. /**
  101539. * Enable or disable the GPU frame time capture
  101540. */
  101541. set: function (value) {
  101542. var _this = this;
  101543. if (value === this._captureGPUFrameTime) {
  101544. return;
  101545. }
  101546. this._captureGPUFrameTime = value;
  101547. if (value) {
  101548. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  101549. if (!_this._gpuFrameTimeToken) {
  101550. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  101551. }
  101552. });
  101553. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  101554. if (!_this._gpuFrameTimeToken) {
  101555. return;
  101556. }
  101557. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  101558. if (time > -1) {
  101559. _this._gpuFrameTimeToken = null;
  101560. _this._gpuFrameTime.fetchNewFrame();
  101561. _this._gpuFrameTime.addCount(time, true);
  101562. }
  101563. });
  101564. }
  101565. else {
  101566. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101567. this._onBeginFrameObserver = null;
  101568. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101569. this._onEndFrameObserver = null;
  101570. }
  101571. },
  101572. enumerable: true,
  101573. configurable: true
  101574. });
  101575. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  101576. /**
  101577. * Gets the perf counter used for shader compilation time
  101578. */
  101579. get: function () {
  101580. return this._shaderCompilationTime;
  101581. },
  101582. enumerable: true,
  101583. configurable: true
  101584. });
  101585. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  101586. /**
  101587. * Gets the shader compilation time capture status
  101588. */
  101589. get: function () {
  101590. return this._captureShaderCompilationTime;
  101591. },
  101592. /**
  101593. * Enable or disable the shader compilation time capture
  101594. */
  101595. set: function (value) {
  101596. var _this = this;
  101597. if (value === this._captureShaderCompilationTime) {
  101598. return;
  101599. }
  101600. this._captureShaderCompilationTime = value;
  101601. if (value) {
  101602. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  101603. _this._shaderCompilationTime.fetchNewFrame();
  101604. _this._shaderCompilationTime.beginMonitoring();
  101605. });
  101606. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  101607. _this._shaderCompilationTime.endMonitoring();
  101608. });
  101609. }
  101610. else {
  101611. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101612. this._onBeforeShaderCompilationObserver = null;
  101613. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101614. this._onAfterShaderCompilationObserver = null;
  101615. }
  101616. },
  101617. enumerable: true,
  101618. configurable: true
  101619. });
  101620. EngineInstrumentation.prototype.dispose = function () {
  101621. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101622. this._onBeginFrameObserver = null;
  101623. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101624. this._onEndFrameObserver = null;
  101625. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101626. this._onBeforeShaderCompilationObserver = null;
  101627. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101628. this._onAfterShaderCompilationObserver = null;
  101629. this.engine = null;
  101630. };
  101631. return EngineInstrumentation;
  101632. }());
  101633. BABYLON.EngineInstrumentation = EngineInstrumentation;
  101634. })(BABYLON || (BABYLON = {}));
  101635. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  101636. var BABYLON;
  101637. (function (BABYLON) {
  101638. /**
  101639. * This class can be used to get instrumentation data from a Babylon engine
  101640. */
  101641. var SceneInstrumentation = /** @class */ (function () {
  101642. function SceneInstrumentation(scene) {
  101643. var _this = this;
  101644. this.scene = scene;
  101645. this._captureActiveMeshesEvaluationTime = false;
  101646. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  101647. this._captureRenderTargetsRenderTime = false;
  101648. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  101649. this._captureFrameTime = false;
  101650. this._frameTime = new BABYLON.PerfCounter();
  101651. this._captureRenderTime = false;
  101652. this._renderTime = new BABYLON.PerfCounter();
  101653. this._captureInterFrameTime = false;
  101654. this._interFrameTime = new BABYLON.PerfCounter();
  101655. this._captureParticlesRenderTime = false;
  101656. this._particlesRenderTime = new BABYLON.PerfCounter();
  101657. this._captureSpritesRenderTime = false;
  101658. this._spritesRenderTime = new BABYLON.PerfCounter();
  101659. this._capturePhysicsTime = false;
  101660. this._physicsTime = new BABYLON.PerfCounter();
  101661. this._captureAnimationsTime = false;
  101662. this._animationsTime = new BABYLON.PerfCounter();
  101663. this._captureCameraRenderTime = false;
  101664. this._cameraRenderTime = new BABYLON.PerfCounter();
  101665. // Observers
  101666. this._onBeforeActiveMeshesEvaluationObserver = null;
  101667. this._onAfterActiveMeshesEvaluationObserver = null;
  101668. this._onBeforeRenderTargetsRenderObserver = null;
  101669. this._onAfterRenderTargetsRenderObserver = null;
  101670. this._onAfterRenderObserver = null;
  101671. this._onBeforeDrawPhaseObserver = null;
  101672. this._onAfterDrawPhaseObserver = null;
  101673. this._onBeforeAnimationsObserver = null;
  101674. this._onBeforeParticlesRenderingObserver = null;
  101675. this._onAfterParticlesRenderingObserver = null;
  101676. this._onBeforeSpritesRenderingObserver = null;
  101677. this._onAfterSpritesRenderingObserver = null;
  101678. this._onBeforePhysicsObserver = null;
  101679. this._onAfterPhysicsObserver = null;
  101680. this._onAfterAnimationsObserver = null;
  101681. this._onBeforeCameraRenderObserver = null;
  101682. this._onAfterCameraRenderObserver = null;
  101683. // Before render
  101684. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  101685. if (_this._captureActiveMeshesEvaluationTime) {
  101686. _this._activeMeshesEvaluationTime.fetchNewFrame();
  101687. }
  101688. if (_this._captureRenderTargetsRenderTime) {
  101689. _this._renderTargetsRenderTime.fetchNewFrame();
  101690. }
  101691. if (_this._captureFrameTime) {
  101692. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  101693. _this._frameTime.beginMonitoring();
  101694. }
  101695. if (_this._captureInterFrameTime) {
  101696. _this._interFrameTime.endMonitoring();
  101697. }
  101698. if (_this._captureParticlesRenderTime) {
  101699. _this._particlesRenderTime.fetchNewFrame();
  101700. }
  101701. if (_this._captureSpritesRenderTime) {
  101702. _this._spritesRenderTime.fetchNewFrame();
  101703. }
  101704. if (_this._captureAnimationsTime) {
  101705. _this._animationsTime.beginMonitoring();
  101706. }
  101707. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  101708. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  101709. });
  101710. // After render
  101711. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  101712. if (_this._captureFrameTime) {
  101713. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  101714. _this._frameTime.endMonitoring();
  101715. }
  101716. if (_this._captureRenderTime) {
  101717. _this._renderTime.endMonitoring(false);
  101718. }
  101719. if (_this._captureInterFrameTime) {
  101720. _this._interFrameTime.beginMonitoring();
  101721. }
  101722. });
  101723. }
  101724. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  101725. // Properties
  101726. /**
  101727. * Gets the perf counter used for active meshes evaluation time
  101728. */
  101729. get: function () {
  101730. return this._activeMeshesEvaluationTime;
  101731. },
  101732. enumerable: true,
  101733. configurable: true
  101734. });
  101735. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  101736. /**
  101737. * Gets the active meshes evaluation time capture status
  101738. */
  101739. get: function () {
  101740. return this._captureActiveMeshesEvaluationTime;
  101741. },
  101742. /**
  101743. * Enable or disable the active meshes evaluation time capture
  101744. */
  101745. set: function (value) {
  101746. var _this = this;
  101747. if (value === this._captureActiveMeshesEvaluationTime) {
  101748. return;
  101749. }
  101750. this._captureActiveMeshesEvaluationTime = value;
  101751. if (value) {
  101752. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  101753. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  101754. _this._activeMeshesEvaluationTime.beginMonitoring();
  101755. });
  101756. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  101757. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  101758. _this._activeMeshesEvaluationTime.endMonitoring();
  101759. });
  101760. }
  101761. else {
  101762. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101763. this._onBeforeActiveMeshesEvaluationObserver = null;
  101764. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101765. this._onAfterActiveMeshesEvaluationObserver = null;
  101766. }
  101767. },
  101768. enumerable: true,
  101769. configurable: true
  101770. });
  101771. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  101772. /**
  101773. * Gets the perf counter used for render targets render time
  101774. */
  101775. get: function () {
  101776. return this._renderTargetsRenderTime;
  101777. },
  101778. enumerable: true,
  101779. configurable: true
  101780. });
  101781. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  101782. /**
  101783. * Gets the render targets render time capture status
  101784. */
  101785. get: function () {
  101786. return this._captureRenderTargetsRenderTime;
  101787. },
  101788. /**
  101789. * Enable or disable the render targets render time capture
  101790. */
  101791. set: function (value) {
  101792. var _this = this;
  101793. if (value === this._captureRenderTargetsRenderTime) {
  101794. return;
  101795. }
  101796. this._captureRenderTargetsRenderTime = value;
  101797. if (value) {
  101798. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  101799. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  101800. _this._renderTargetsRenderTime.beginMonitoring();
  101801. });
  101802. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  101803. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  101804. _this._renderTargetsRenderTime.endMonitoring(false);
  101805. });
  101806. }
  101807. else {
  101808. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101809. this._onBeforeRenderTargetsRenderObserver = null;
  101810. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101811. this._onAfterRenderTargetsRenderObserver = null;
  101812. }
  101813. },
  101814. enumerable: true,
  101815. configurable: true
  101816. });
  101817. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  101818. /**
  101819. * Gets the perf counter used for particles render time
  101820. */
  101821. get: function () {
  101822. return this._particlesRenderTime;
  101823. },
  101824. enumerable: true,
  101825. configurable: true
  101826. });
  101827. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  101828. /**
  101829. * Gets the particles render time capture status
  101830. */
  101831. get: function () {
  101832. return this._captureParticlesRenderTime;
  101833. },
  101834. /**
  101835. * Enable or disable the particles render time capture
  101836. */
  101837. set: function (value) {
  101838. var _this = this;
  101839. if (value === this._captureParticlesRenderTime) {
  101840. return;
  101841. }
  101842. this._captureParticlesRenderTime = value;
  101843. if (value) {
  101844. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101845. BABYLON.Tools.StartPerformanceCounter("Particles");
  101846. _this._particlesRenderTime.beginMonitoring();
  101847. });
  101848. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101849. BABYLON.Tools.EndPerformanceCounter("Particles");
  101850. _this._particlesRenderTime.endMonitoring(false);
  101851. });
  101852. }
  101853. else {
  101854. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101855. this._onBeforeParticlesRenderingObserver = null;
  101856. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101857. this._onAfterParticlesRenderingObserver = null;
  101858. }
  101859. },
  101860. enumerable: true,
  101861. configurable: true
  101862. });
  101863. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101864. /**
  101865. * Gets the perf counter used for sprites render time
  101866. */
  101867. get: function () {
  101868. return this._spritesRenderTime;
  101869. },
  101870. enumerable: true,
  101871. configurable: true
  101872. });
  101873. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101874. /**
  101875. * Gets the sprites render time capture status
  101876. */
  101877. get: function () {
  101878. return this._captureSpritesRenderTime;
  101879. },
  101880. /**
  101881. * Enable or disable the sprites render time capture
  101882. */
  101883. set: function (value) {
  101884. var _this = this;
  101885. if (value === this._captureSpritesRenderTime) {
  101886. return;
  101887. }
  101888. this._captureSpritesRenderTime = value;
  101889. if (value) {
  101890. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101891. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101892. _this._spritesRenderTime.beginMonitoring();
  101893. });
  101894. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101895. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101896. _this._spritesRenderTime.endMonitoring(false);
  101897. });
  101898. }
  101899. else {
  101900. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101901. this._onBeforeSpritesRenderingObserver = null;
  101902. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101903. this._onAfterSpritesRenderingObserver = null;
  101904. }
  101905. },
  101906. enumerable: true,
  101907. configurable: true
  101908. });
  101909. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101910. /**
  101911. * Gets the perf counter used for physics time
  101912. */
  101913. get: function () {
  101914. return this._physicsTime;
  101915. },
  101916. enumerable: true,
  101917. configurable: true
  101918. });
  101919. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101920. /**
  101921. * Gets the physics time capture status
  101922. */
  101923. get: function () {
  101924. return this._capturePhysicsTime;
  101925. },
  101926. /**
  101927. * Enable or disable the physics time capture
  101928. */
  101929. set: function (value) {
  101930. var _this = this;
  101931. if (value === this._capturePhysicsTime) {
  101932. return;
  101933. }
  101934. this._capturePhysicsTime = value;
  101935. if (value) {
  101936. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101937. BABYLON.Tools.StartPerformanceCounter("Physics");
  101938. _this._physicsTime.beginMonitoring();
  101939. });
  101940. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101941. BABYLON.Tools.EndPerformanceCounter("Physics");
  101942. _this._physicsTime.endMonitoring();
  101943. });
  101944. }
  101945. else {
  101946. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101947. this._onBeforePhysicsObserver = null;
  101948. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101949. this._onAfterPhysicsObserver = null;
  101950. }
  101951. },
  101952. enumerable: true,
  101953. configurable: true
  101954. });
  101955. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101956. /**
  101957. * Gets the perf counter used for animations time
  101958. */
  101959. get: function () {
  101960. return this._animationsTime;
  101961. },
  101962. enumerable: true,
  101963. configurable: true
  101964. });
  101965. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101966. /**
  101967. * Gets the animations time capture status
  101968. */
  101969. get: function () {
  101970. return this._captureAnimationsTime;
  101971. },
  101972. /**
  101973. * Enable or disable the animations time capture
  101974. */
  101975. set: function (value) {
  101976. var _this = this;
  101977. if (value === this._captureAnimationsTime) {
  101978. return;
  101979. }
  101980. this._captureAnimationsTime = value;
  101981. if (value) {
  101982. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101983. _this._animationsTime.endMonitoring();
  101984. });
  101985. }
  101986. else {
  101987. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101988. this._onAfterAnimationsObserver = null;
  101989. }
  101990. },
  101991. enumerable: true,
  101992. configurable: true
  101993. });
  101994. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101995. /**
  101996. * Gets the perf counter used for frame time capture
  101997. */
  101998. get: function () {
  101999. return this._frameTime;
  102000. },
  102001. enumerable: true,
  102002. configurable: true
  102003. });
  102004. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  102005. /**
  102006. * Gets the frame time capture status
  102007. */
  102008. get: function () {
  102009. return this._captureFrameTime;
  102010. },
  102011. /**
  102012. * Enable or disable the frame time capture
  102013. */
  102014. set: function (value) {
  102015. this._captureFrameTime = value;
  102016. },
  102017. enumerable: true,
  102018. configurable: true
  102019. });
  102020. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  102021. /**
  102022. * Gets the perf counter used for inter-frames time capture
  102023. */
  102024. get: function () {
  102025. return this._interFrameTime;
  102026. },
  102027. enumerable: true,
  102028. configurable: true
  102029. });
  102030. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  102031. /**
  102032. * Gets the inter-frames time capture status
  102033. */
  102034. get: function () {
  102035. return this._captureInterFrameTime;
  102036. },
  102037. /**
  102038. * Enable or disable the inter-frames time capture
  102039. */
  102040. set: function (value) {
  102041. this._captureInterFrameTime = value;
  102042. },
  102043. enumerable: true,
  102044. configurable: true
  102045. });
  102046. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  102047. /**
  102048. * Gets the perf counter used for render time capture
  102049. */
  102050. get: function () {
  102051. return this._renderTime;
  102052. },
  102053. enumerable: true,
  102054. configurable: true
  102055. });
  102056. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  102057. /**
  102058. * Gets the render time capture status
  102059. */
  102060. get: function () {
  102061. return this._captureRenderTime;
  102062. },
  102063. /**
  102064. * Enable or disable the render time capture
  102065. */
  102066. set: function (value) {
  102067. var _this = this;
  102068. if (value === this._captureRenderTime) {
  102069. return;
  102070. }
  102071. this._captureRenderTime = value;
  102072. if (value) {
  102073. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  102074. _this._renderTime.beginMonitoring();
  102075. BABYLON.Tools.StartPerformanceCounter("Main render");
  102076. });
  102077. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  102078. _this._renderTime.endMonitoring(false);
  102079. BABYLON.Tools.EndPerformanceCounter("Main render");
  102080. });
  102081. }
  102082. else {
  102083. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102084. this._onBeforeDrawPhaseObserver = null;
  102085. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102086. this._onAfterDrawPhaseObserver = null;
  102087. }
  102088. },
  102089. enumerable: true,
  102090. configurable: true
  102091. });
  102092. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  102093. /**
  102094. * Gets the perf counter used for camera render time capture
  102095. */
  102096. get: function () {
  102097. return this._cameraRenderTime;
  102098. },
  102099. enumerable: true,
  102100. configurable: true
  102101. });
  102102. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  102103. /**
  102104. * Gets the camera render time capture status
  102105. */
  102106. get: function () {
  102107. return this._captureCameraRenderTime;
  102108. },
  102109. /**
  102110. * Enable or disable the camera render time capture
  102111. */
  102112. set: function (value) {
  102113. var _this = this;
  102114. if (value === this._captureCameraRenderTime) {
  102115. return;
  102116. }
  102117. this._captureCameraRenderTime = value;
  102118. if (value) {
  102119. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  102120. _this._cameraRenderTime.beginMonitoring();
  102121. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  102122. });
  102123. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  102124. _this._cameraRenderTime.endMonitoring(false);
  102125. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  102126. });
  102127. }
  102128. else {
  102129. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102130. this._onBeforeCameraRenderObserver = null;
  102131. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102132. this._onAfterCameraRenderObserver = null;
  102133. }
  102134. },
  102135. enumerable: true,
  102136. configurable: true
  102137. });
  102138. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  102139. /**
  102140. * Gets the perf counter used for draw calls
  102141. */
  102142. get: function () {
  102143. return this.scene.getEngine()._drawCalls;
  102144. },
  102145. enumerable: true,
  102146. configurable: true
  102147. });
  102148. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  102149. /**
  102150. * Gets the perf counter used for texture collisions
  102151. */
  102152. get: function () {
  102153. return this.scene.getEngine()._textureCollisions;
  102154. },
  102155. enumerable: true,
  102156. configurable: true
  102157. });
  102158. SceneInstrumentation.prototype.dispose = function () {
  102159. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102160. this._onAfterRenderObserver = null;
  102161. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102162. this._onBeforeActiveMeshesEvaluationObserver = null;
  102163. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102164. this._onAfterActiveMeshesEvaluationObserver = null;
  102165. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102166. this._onBeforeRenderTargetsRenderObserver = null;
  102167. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102168. this._onAfterRenderTargetsRenderObserver = null;
  102169. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  102170. this._onBeforeAnimationsObserver = null;
  102171. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102172. this._onBeforeParticlesRenderingObserver = null;
  102173. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102174. this._onAfterParticlesRenderingObserver = null;
  102175. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102176. this._onBeforeSpritesRenderingObserver = null;
  102177. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102178. this._onAfterSpritesRenderingObserver = null;
  102179. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102180. this._onBeforeDrawPhaseObserver = null;
  102181. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102182. this._onAfterDrawPhaseObserver = null;
  102183. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102184. this._onBeforePhysicsObserver = null;
  102185. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102186. this._onAfterPhysicsObserver = null;
  102187. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102188. this._onAfterAnimationsObserver = null;
  102189. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102190. this._onBeforeCameraRenderObserver = null;
  102191. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102192. this._onAfterCameraRenderObserver = null;
  102193. this.scene = null;
  102194. };
  102195. return SceneInstrumentation;
  102196. }());
  102197. BABYLON.SceneInstrumentation = SceneInstrumentation;
  102198. })(BABYLON || (BABYLON = {}));
  102199. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  102200. var BABYLON;
  102201. (function (BABYLON) {
  102202. /**
  102203. * @hidden
  102204. **/
  102205. var _TimeToken = /** @class */ (function () {
  102206. function _TimeToken() {
  102207. this._timeElapsedQueryEnded = false;
  102208. }
  102209. return _TimeToken;
  102210. }());
  102211. BABYLON._TimeToken = _TimeToken;
  102212. })(BABYLON || (BABYLON = {}));
  102213. //# sourceMappingURL=babylon.timeToken.js.map
  102214. var BABYLON;
  102215. (function (BABYLON) {
  102216. /**
  102217. * Background material defines definition.
  102218. * @hidden Mainly internal Use
  102219. */
  102220. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  102221. __extends(BackgroundMaterialDefines, _super);
  102222. /**
  102223. * Constructor of the defines.
  102224. */
  102225. function BackgroundMaterialDefines() {
  102226. var _this = _super.call(this) || this;
  102227. /**
  102228. * True if the diffuse texture is in use.
  102229. */
  102230. _this.DIFFUSE = false;
  102231. /**
  102232. * The direct UV channel to use.
  102233. */
  102234. _this.DIFFUSEDIRECTUV = 0;
  102235. /**
  102236. * True if the diffuse texture is in gamma space.
  102237. */
  102238. _this.GAMMADIFFUSE = false;
  102239. /**
  102240. * True if the diffuse texture has opacity in the alpha channel.
  102241. */
  102242. _this.DIFFUSEHASALPHA = false;
  102243. /**
  102244. * True if you want the material to fade to transparent at grazing angle.
  102245. */
  102246. _this.OPACITYFRESNEL = false;
  102247. /**
  102248. * True if an extra blur needs to be added in the reflection.
  102249. */
  102250. _this.REFLECTIONBLUR = false;
  102251. /**
  102252. * True if you want the material to fade to reflection at grazing angle.
  102253. */
  102254. _this.REFLECTIONFRESNEL = false;
  102255. /**
  102256. * True if you want the material to falloff as far as you move away from the scene center.
  102257. */
  102258. _this.REFLECTIONFALLOFF = false;
  102259. /**
  102260. * False if the current Webgl implementation does not support the texture lod extension.
  102261. */
  102262. _this.TEXTURELODSUPPORT = false;
  102263. /**
  102264. * True to ensure the data are premultiplied.
  102265. */
  102266. _this.PREMULTIPLYALPHA = false;
  102267. /**
  102268. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  102269. */
  102270. _this.USERGBCOLOR = false;
  102271. /**
  102272. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  102273. * stays aligned with the desired configuration.
  102274. */
  102275. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  102276. /**
  102277. * True to add noise in order to reduce the banding effect.
  102278. */
  102279. _this.NOISE = false;
  102280. /**
  102281. * is the reflection texture in BGR color scheme?
  102282. * Mainly used to solve a bug in ios10 video tag
  102283. */
  102284. _this.REFLECTIONBGR = false;
  102285. _this.IMAGEPROCESSING = false;
  102286. _this.VIGNETTE = false;
  102287. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  102288. _this.VIGNETTEBLENDMODEOPAQUE = false;
  102289. _this.TONEMAPPING = false;
  102290. _this.CONTRAST = false;
  102291. _this.COLORCURVES = false;
  102292. _this.COLORGRADING = false;
  102293. _this.COLORGRADING3D = false;
  102294. _this.SAMPLER3DGREENDEPTH = false;
  102295. _this.SAMPLER3DBGRMAP = false;
  102296. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  102297. _this.EXPOSURE = false;
  102298. // Reflection.
  102299. _this.REFLECTION = false;
  102300. _this.REFLECTIONMAP_3D = false;
  102301. _this.REFLECTIONMAP_SPHERICAL = false;
  102302. _this.REFLECTIONMAP_PLANAR = false;
  102303. _this.REFLECTIONMAP_CUBIC = false;
  102304. _this.REFLECTIONMAP_PROJECTION = false;
  102305. _this.REFLECTIONMAP_SKYBOX = false;
  102306. _this.REFLECTIONMAP_EXPLICIT = false;
  102307. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102308. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102309. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102310. _this.INVERTCUBICMAP = false;
  102311. _this.REFLECTIONMAP_OPPOSITEZ = false;
  102312. _this.LODINREFLECTIONALPHA = false;
  102313. _this.GAMMAREFLECTION = false;
  102314. _this.RGBDREFLECTION = false;
  102315. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  102316. // Default BJS.
  102317. _this.MAINUV1 = false;
  102318. _this.MAINUV2 = false;
  102319. _this.UV1 = false;
  102320. _this.UV2 = false;
  102321. _this.CLIPPLANE = false;
  102322. _this.POINTSIZE = false;
  102323. _this.FOG = false;
  102324. _this.NORMAL = false;
  102325. _this.NUM_BONE_INFLUENCERS = 0;
  102326. _this.BonesPerMesh = 0;
  102327. _this.INSTANCES = false;
  102328. _this.SHADOWFLOAT = false;
  102329. _this.rebuild();
  102330. return _this;
  102331. }
  102332. return BackgroundMaterialDefines;
  102333. }(BABYLON.MaterialDefines));
  102334. /**
  102335. * Background material used to create an efficient environement around your scene.
  102336. */
  102337. var BackgroundMaterial = /** @class */ (function (_super) {
  102338. __extends(BackgroundMaterial, _super);
  102339. /**
  102340. * Instantiates a Background Material in the given scene
  102341. * @param name The friendly name of the material
  102342. * @param scene The scene to add the material to
  102343. */
  102344. function BackgroundMaterial(name, scene) {
  102345. var _this = _super.call(this, name, scene) || this;
  102346. /**
  102347. * Key light Color (multiply against the environement texture)
  102348. */
  102349. _this.primaryColor = BABYLON.Color3.White();
  102350. _this._primaryColorShadowLevel = 0;
  102351. _this._primaryColorHighlightLevel = 0;
  102352. /**
  102353. * Reflection Texture used in the material.
  102354. * Should be author in a specific way for the best result (refer to the documentation).
  102355. */
  102356. _this.reflectionTexture = null;
  102357. /**
  102358. * Reflection Texture level of blur.
  102359. *
  102360. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  102361. * texture twice.
  102362. */
  102363. _this.reflectionBlur = 0;
  102364. /**
  102365. * Diffuse Texture used in the material.
  102366. * Should be author in a specific way for the best result (refer to the documentation).
  102367. */
  102368. _this.diffuseTexture = null;
  102369. _this._shadowLights = null;
  102370. /**
  102371. * Specify the list of lights casting shadow on the material.
  102372. * All scene shadow lights will be included if null.
  102373. */
  102374. _this.shadowLights = null;
  102375. /**
  102376. * Helps adjusting the shadow to a softer level if required.
  102377. * 0 means black shadows and 1 means no shadows.
  102378. */
  102379. _this.shadowLevel = 0;
  102380. /**
  102381. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  102382. * It is usually zero but might be interesting to modify according to your setup.
  102383. */
  102384. _this.sceneCenter = BABYLON.Vector3.Zero();
  102385. /**
  102386. * This helps specifying that the material is falling off to the sky box at grazing angle.
  102387. * This helps ensuring a nice transition when the camera goes under the ground.
  102388. */
  102389. _this.opacityFresnel = true;
  102390. /**
  102391. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  102392. * This helps adding a mirror texture on the ground.
  102393. */
  102394. _this.reflectionFresnel = false;
  102395. /**
  102396. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  102397. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  102398. */
  102399. _this.reflectionFalloffDistance = 0.0;
  102400. /**
  102401. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  102402. */
  102403. _this.reflectionAmount = 1.0;
  102404. /**
  102405. * This specifies the weight of the reflection at grazing angle.
  102406. */
  102407. _this.reflectionReflectance0 = 0.05;
  102408. /**
  102409. * This specifies the weight of the reflection at a perpendicular point of view.
  102410. */
  102411. _this.reflectionReflectance90 = 0.5;
  102412. /**
  102413. * Helps to directly use the maps channels instead of their level.
  102414. */
  102415. _this.useRGBColor = true;
  102416. /**
  102417. * This helps reducing the banding effect that could occur on the background.
  102418. */
  102419. _this.enableNoise = false;
  102420. _this._fovMultiplier = 1.0;
  102421. /**
  102422. * Enable the FOV adjustment feature controlled by fovMultiplier.
  102423. */
  102424. _this.useEquirectangularFOV = false;
  102425. _this._maxSimultaneousLights = 4;
  102426. /**
  102427. * Number of Simultaneous lights allowed on the material.
  102428. */
  102429. _this.maxSimultaneousLights = 4;
  102430. /**
  102431. * Keep track of the image processing observer to allow dispose and replace.
  102432. */
  102433. _this._imageProcessingObserver = null;
  102434. /**
  102435. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  102436. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  102437. */
  102438. _this.switchToBGR = false;
  102439. // Temp values kept as cache in the material.
  102440. _this._renderTargets = new BABYLON.SmartArray(16);
  102441. _this._reflectionControls = BABYLON.Vector4.Zero();
  102442. _this._white = BABYLON.Color3.White();
  102443. _this._primaryShadowColor = BABYLON.Color3.Black();
  102444. _this._primaryHighlightColor = BABYLON.Color3.Black();
  102445. // Setup the default processing configuration to the scene.
  102446. _this._attachImageProcessingConfiguration(null);
  102447. _this.getRenderTargetTextures = function () {
  102448. _this._renderTargets.reset();
  102449. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  102450. _this._renderTargets.push(_this._diffuseTexture);
  102451. }
  102452. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  102453. _this._renderTargets.push(_this._reflectionTexture);
  102454. }
  102455. return _this._renderTargets;
  102456. };
  102457. return _this;
  102458. }
  102459. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  102460. /**
  102461. * Experimental Internal Use Only.
  102462. *
  102463. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  102464. * This acts as a helper to set the primary color to a more "human friendly" value.
  102465. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  102466. * output color as close as possible from the chosen value.
  102467. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  102468. * part of lighting setup.)
  102469. */
  102470. get: function () {
  102471. return this.__perceptualColor;
  102472. },
  102473. set: function (value) {
  102474. this.__perceptualColor = value;
  102475. this._computePrimaryColorFromPerceptualColor();
  102476. this._markAllSubMeshesAsLightsDirty();
  102477. },
  102478. enumerable: true,
  102479. configurable: true
  102480. });
  102481. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  102482. /**
  102483. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  102484. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  102485. */
  102486. get: function () {
  102487. return this._primaryColorShadowLevel;
  102488. },
  102489. set: function (value) {
  102490. this._primaryColorShadowLevel = value;
  102491. this._computePrimaryColors();
  102492. this._markAllSubMeshesAsLightsDirty();
  102493. },
  102494. enumerable: true,
  102495. configurable: true
  102496. });
  102497. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  102498. /**
  102499. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  102500. * The primary color is used at the level chosen to define what the white area would look.
  102501. */
  102502. get: function () {
  102503. return this._primaryColorHighlightLevel;
  102504. },
  102505. set: function (value) {
  102506. this._primaryColorHighlightLevel = value;
  102507. this._computePrimaryColors();
  102508. this._markAllSubMeshesAsLightsDirty();
  102509. },
  102510. enumerable: true,
  102511. configurable: true
  102512. });
  102513. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  102514. /**
  102515. * Sets the reflection reflectance fresnel values according to the default standard
  102516. * empirically know to work well :-)
  102517. */
  102518. set: function (value) {
  102519. var reflectionWeight = value;
  102520. if (reflectionWeight < 0.5) {
  102521. reflectionWeight = reflectionWeight * 2.0;
  102522. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  102523. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  102524. }
  102525. else {
  102526. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  102527. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  102528. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  102529. }
  102530. },
  102531. enumerable: true,
  102532. configurable: true
  102533. });
  102534. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  102535. /**
  102536. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102537. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  102538. * Recommended to be keep at 1.0 except for special cases.
  102539. */
  102540. get: function () {
  102541. return this._fovMultiplier;
  102542. },
  102543. set: function (value) {
  102544. if (isNaN(value)) {
  102545. value = 1.0;
  102546. }
  102547. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  102548. },
  102549. enumerable: true,
  102550. configurable: true
  102551. });
  102552. /**
  102553. * Attaches a new image processing configuration to the PBR Material.
  102554. * @param configuration (if null the scene configuration will be use)
  102555. */
  102556. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  102557. var _this = this;
  102558. if (configuration === this._imageProcessingConfiguration) {
  102559. return;
  102560. }
  102561. // Detaches observer.
  102562. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102563. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102564. }
  102565. // Pick the scene configuration if needed.
  102566. if (!configuration) {
  102567. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  102568. }
  102569. else {
  102570. this._imageProcessingConfiguration = configuration;
  102571. }
  102572. // Attaches observer.
  102573. if (this._imageProcessingConfiguration) {
  102574. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  102575. _this._computePrimaryColorFromPerceptualColor();
  102576. _this._markAllSubMeshesAsImageProcessingDirty();
  102577. });
  102578. }
  102579. };
  102580. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  102581. /**
  102582. * Gets the image processing configuration used either in this material.
  102583. */
  102584. get: function () {
  102585. return this._imageProcessingConfiguration;
  102586. },
  102587. /**
  102588. * Sets the Default image processing configuration used either in the this material.
  102589. *
  102590. * If sets to null, the scene one is in use.
  102591. */
  102592. set: function (value) {
  102593. this._attachImageProcessingConfiguration(value);
  102594. // Ensure the effect will be rebuilt.
  102595. this._markAllSubMeshesAsTexturesDirty();
  102596. },
  102597. enumerable: true,
  102598. configurable: true
  102599. });
  102600. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  102601. /**
  102602. * Gets wether the color curves effect is enabled.
  102603. */
  102604. get: function () {
  102605. return this.imageProcessingConfiguration.colorCurvesEnabled;
  102606. },
  102607. /**
  102608. * Sets wether the color curves effect is enabled.
  102609. */
  102610. set: function (value) {
  102611. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  102612. },
  102613. enumerable: true,
  102614. configurable: true
  102615. });
  102616. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  102617. /**
  102618. * Gets wether the color grading effect is enabled.
  102619. */
  102620. get: function () {
  102621. return this.imageProcessingConfiguration.colorGradingEnabled;
  102622. },
  102623. /**
  102624. * Gets wether the color grading effect is enabled.
  102625. */
  102626. set: function (value) {
  102627. this.imageProcessingConfiguration.colorGradingEnabled = value;
  102628. },
  102629. enumerable: true,
  102630. configurable: true
  102631. });
  102632. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  102633. /**
  102634. * Gets wether tonemapping is enabled or not.
  102635. */
  102636. get: function () {
  102637. return this._imageProcessingConfiguration.toneMappingEnabled;
  102638. },
  102639. /**
  102640. * Sets wether tonemapping is enabled or not
  102641. */
  102642. set: function (value) {
  102643. this._imageProcessingConfiguration.toneMappingEnabled = value;
  102644. },
  102645. enumerable: true,
  102646. configurable: true
  102647. });
  102648. ;
  102649. ;
  102650. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  102651. /**
  102652. * The camera exposure used on this material.
  102653. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102654. * This corresponds to a photographic exposure.
  102655. */
  102656. get: function () {
  102657. return this._imageProcessingConfiguration.exposure;
  102658. },
  102659. /**
  102660. * The camera exposure used on this material.
  102661. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102662. * This corresponds to a photographic exposure.
  102663. */
  102664. set: function (value) {
  102665. this._imageProcessingConfiguration.exposure = value;
  102666. },
  102667. enumerable: true,
  102668. configurable: true
  102669. });
  102670. ;
  102671. ;
  102672. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  102673. /**
  102674. * Gets The camera contrast used on this material.
  102675. */
  102676. get: function () {
  102677. return this._imageProcessingConfiguration.contrast;
  102678. },
  102679. /**
  102680. * Sets The camera contrast used on this material.
  102681. */
  102682. set: function (value) {
  102683. this._imageProcessingConfiguration.contrast = value;
  102684. },
  102685. enumerable: true,
  102686. configurable: true
  102687. });
  102688. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  102689. /**
  102690. * Gets the Color Grading 2D Lookup Texture.
  102691. */
  102692. get: function () {
  102693. return this._imageProcessingConfiguration.colorGradingTexture;
  102694. },
  102695. /**
  102696. * Sets the Color Grading 2D Lookup Texture.
  102697. */
  102698. set: function (value) {
  102699. this.imageProcessingConfiguration.colorGradingTexture = value;
  102700. },
  102701. enumerable: true,
  102702. configurable: true
  102703. });
  102704. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  102705. /**
  102706. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102707. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102708. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  102709. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102710. */
  102711. get: function () {
  102712. return this.imageProcessingConfiguration.colorCurves;
  102713. },
  102714. /**
  102715. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102716. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102717. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  102718. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102719. */
  102720. set: function (value) {
  102721. this.imageProcessingConfiguration.colorCurves = value;
  102722. },
  102723. enumerable: true,
  102724. configurable: true
  102725. });
  102726. /**
  102727. * The entire material has been created in order to prevent overdraw.
  102728. * @returns false
  102729. */
  102730. BackgroundMaterial.prototype.needAlphaTesting = function () {
  102731. return true;
  102732. };
  102733. /**
  102734. * The entire material has been created in order to prevent overdraw.
  102735. * @returns true if blending is enable
  102736. */
  102737. BackgroundMaterial.prototype.needAlphaBlending = function () {
  102738. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  102739. };
  102740. /**
  102741. * Checks wether the material is ready to be rendered for a given mesh.
  102742. * @param mesh The mesh to render
  102743. * @param subMesh The submesh to check against
  102744. * @param useInstances Specify wether or not the material is used with instances
  102745. * @returns true if all the dependencies are ready (Textures, Effects...)
  102746. */
  102747. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  102748. var _this = this;
  102749. if (useInstances === void 0) { useInstances = false; }
  102750. if (subMesh.effect && this.isFrozen) {
  102751. if (this._wasPreviouslyReady) {
  102752. return true;
  102753. }
  102754. }
  102755. if (!subMesh._materialDefines) {
  102756. subMesh._materialDefines = new BackgroundMaterialDefines();
  102757. }
  102758. var scene = this.getScene();
  102759. var defines = subMesh._materialDefines;
  102760. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  102761. if (defines._renderId === scene.getRenderId()) {
  102762. return true;
  102763. }
  102764. }
  102765. var engine = scene.getEngine();
  102766. // Lights
  102767. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  102768. defines._needNormals = true;
  102769. // Textures
  102770. if (defines._areTexturesDirty) {
  102771. defines._needUVs = false;
  102772. if (scene.texturesEnabled) {
  102773. if (scene.getEngine().getCaps().textureLOD) {
  102774. defines.TEXTURELODSUPPORT = true;
  102775. }
  102776. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102777. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  102778. return false;
  102779. }
  102780. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  102781. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  102782. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  102783. defines.OPACITYFRESNEL = this._opacityFresnel;
  102784. }
  102785. else {
  102786. defines.DIFFUSE = false;
  102787. defines.DIFFUSEHASALPHA = false;
  102788. defines.GAMMADIFFUSE = false;
  102789. defines.OPACITYFRESNEL = false;
  102790. }
  102791. var reflectionTexture = this._reflectionTexture;
  102792. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102793. if (!reflectionTexture.isReadyOrNotBlocking()) {
  102794. return false;
  102795. }
  102796. defines.REFLECTION = true;
  102797. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  102798. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  102799. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  102800. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  102801. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  102802. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  102803. defines.REFLECTIONBGR = this.switchToBGR;
  102804. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  102805. defines.INVERTCUBICMAP = true;
  102806. }
  102807. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  102808. switch (reflectionTexture.coordinatesMode) {
  102809. case BABYLON.Texture.EXPLICIT_MODE:
  102810. defines.REFLECTIONMAP_EXPLICIT = true;
  102811. break;
  102812. case BABYLON.Texture.PLANAR_MODE:
  102813. defines.REFLECTIONMAP_PLANAR = true;
  102814. break;
  102815. case BABYLON.Texture.PROJECTION_MODE:
  102816. defines.REFLECTIONMAP_PROJECTION = true;
  102817. break;
  102818. case BABYLON.Texture.SKYBOX_MODE:
  102819. defines.REFLECTIONMAP_SKYBOX = true;
  102820. break;
  102821. case BABYLON.Texture.SPHERICAL_MODE:
  102822. defines.REFLECTIONMAP_SPHERICAL = true;
  102823. break;
  102824. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  102825. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  102826. break;
  102827. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  102828. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102829. break;
  102830. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102831. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102832. break;
  102833. case BABYLON.Texture.CUBIC_MODE:
  102834. case BABYLON.Texture.INVCUBIC_MODE:
  102835. default:
  102836. defines.REFLECTIONMAP_CUBIC = true;
  102837. break;
  102838. }
  102839. if (this.reflectionFresnel) {
  102840. defines.REFLECTIONFRESNEL = true;
  102841. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102842. this._reflectionControls.x = this.reflectionAmount;
  102843. this._reflectionControls.y = this.reflectionReflectance0;
  102844. this._reflectionControls.z = this.reflectionReflectance90;
  102845. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102846. }
  102847. else {
  102848. defines.REFLECTIONFRESNEL = false;
  102849. defines.REFLECTIONFALLOFF = false;
  102850. }
  102851. }
  102852. else {
  102853. defines.REFLECTION = false;
  102854. defines.REFLECTIONFRESNEL = false;
  102855. defines.REFLECTIONFALLOFF = false;
  102856. defines.REFLECTIONBLUR = false;
  102857. defines.REFLECTIONMAP_3D = false;
  102858. defines.REFLECTIONMAP_SPHERICAL = false;
  102859. defines.REFLECTIONMAP_PLANAR = false;
  102860. defines.REFLECTIONMAP_CUBIC = false;
  102861. defines.REFLECTIONMAP_PROJECTION = false;
  102862. defines.REFLECTIONMAP_SKYBOX = false;
  102863. defines.REFLECTIONMAP_EXPLICIT = false;
  102864. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102865. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102866. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102867. defines.INVERTCUBICMAP = false;
  102868. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102869. defines.LODINREFLECTIONALPHA = false;
  102870. defines.GAMMAREFLECTION = false;
  102871. defines.RGBDREFLECTION = false;
  102872. }
  102873. }
  102874. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102875. defines.USERGBCOLOR = this._useRGBColor;
  102876. defines.NOISE = this._enableNoise;
  102877. }
  102878. if (defines._areLightsDirty) {
  102879. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102880. }
  102881. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102882. if (!this._imageProcessingConfiguration.isReady()) {
  102883. return false;
  102884. }
  102885. this._imageProcessingConfiguration.prepareDefines(defines);
  102886. }
  102887. // Misc.
  102888. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102889. // Values that need to be evaluated on every frame
  102890. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102891. // Attribs
  102892. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102893. if (mesh) {
  102894. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102895. mesh.createNormals(true);
  102896. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102897. }
  102898. }
  102899. }
  102900. // Get correct effect
  102901. if (defines.isDirty) {
  102902. defines.markAsProcessed();
  102903. scene.resetCachedMaterial();
  102904. // Fallbacks
  102905. var fallbacks = new BABYLON.EffectFallbacks();
  102906. if (defines.FOG) {
  102907. fallbacks.addFallback(0, "FOG");
  102908. }
  102909. if (defines.POINTSIZE) {
  102910. fallbacks.addFallback(1, "POINTSIZE");
  102911. }
  102912. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102913. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102914. fallbacks.addCPUSkinningFallback(0, mesh);
  102915. }
  102916. //Attributes
  102917. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102918. if (defines.NORMAL) {
  102919. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102920. }
  102921. if (defines.UV1) {
  102922. attribs.push(BABYLON.VertexBuffer.UVKind);
  102923. }
  102924. if (defines.UV2) {
  102925. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102926. }
  102927. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102928. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102929. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102930. "vFogInfos", "vFogColor", "pointSize",
  102931. "vClipPlane", "mBones",
  102932. "vPrimaryColor", "vPrimaryColorShadow",
  102933. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102934. "shadowLevel", "alpha",
  102935. "vBackgroundCenter", "vReflectionControl",
  102936. "vDiffuseInfos", "diffuseMatrix",
  102937. ];
  102938. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102939. var uniformBuffers = ["Material", "Scene"];
  102940. if (BABYLON.ImageProcessingConfiguration) {
  102941. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102942. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102943. }
  102944. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102945. uniformsNames: uniforms,
  102946. uniformBuffersNames: uniformBuffers,
  102947. samplers: samplers,
  102948. defines: defines,
  102949. maxSimultaneousLights: this._maxSimultaneousLights
  102950. });
  102951. var onCompiled = function (effect) {
  102952. if (_this.onCompiled) {
  102953. _this.onCompiled(effect);
  102954. }
  102955. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102956. };
  102957. var join = defines.toString();
  102958. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102959. attributes: attribs,
  102960. uniformsNames: uniforms,
  102961. uniformBuffersNames: uniformBuffers,
  102962. samplers: samplers,
  102963. defines: join,
  102964. fallbacks: fallbacks,
  102965. onCompiled: onCompiled,
  102966. onError: this.onError,
  102967. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102968. }, engine), defines);
  102969. this.buildUniformLayout();
  102970. }
  102971. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102972. return false;
  102973. }
  102974. defines._renderId = scene.getRenderId();
  102975. this._wasPreviouslyReady = true;
  102976. return true;
  102977. };
  102978. /**
  102979. * Compute the primary color according to the chosen perceptual color.
  102980. */
  102981. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102982. if (!this.__perceptualColor) {
  102983. return;
  102984. }
  102985. this._primaryColor.copyFrom(this.__perceptualColor);
  102986. // Revert gamma space.
  102987. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102988. // Revert image processing configuration.
  102989. if (this._imageProcessingConfiguration) {
  102990. // Revert Exposure.
  102991. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102992. }
  102993. this._computePrimaryColors();
  102994. };
  102995. /**
  102996. * Compute the highlights and shadow colors according to their chosen levels.
  102997. */
  102998. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102999. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  103000. return;
  103001. }
  103002. // Find the highlight color based on the configuration.
  103003. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  103004. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  103005. // Find the shadow color based on the configuration.
  103006. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  103007. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  103008. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  103009. };
  103010. /**
  103011. * Build the uniform buffer used in the material.
  103012. */
  103013. BackgroundMaterial.prototype.buildUniformLayout = function () {
  103014. // Order is important !
  103015. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  103016. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  103017. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  103018. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  103019. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  103020. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  103021. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  103022. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  103023. this._uniformBuffer.addUniform("pointSize", 1);
  103024. this._uniformBuffer.addUniform("shadowLevel", 1);
  103025. this._uniformBuffer.addUniform("alpha", 1);
  103026. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  103027. this._uniformBuffer.addUniform("vReflectionControl", 4);
  103028. this._uniformBuffer.create();
  103029. };
  103030. /**
  103031. * Unbind the material.
  103032. */
  103033. BackgroundMaterial.prototype.unbind = function () {
  103034. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  103035. this._uniformBuffer.setTexture("diffuseSampler", null);
  103036. }
  103037. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  103038. this._uniformBuffer.setTexture("reflectionSampler", null);
  103039. }
  103040. _super.prototype.unbind.call(this);
  103041. };
  103042. /**
  103043. * Bind only the world matrix to the material.
  103044. * @param world The world matrix to bind.
  103045. */
  103046. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  103047. this._activeEffect.setMatrix("world", world);
  103048. };
  103049. /**
  103050. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  103051. * @param world The world matrix to bind.
  103052. * @param subMesh The submesh to bind for.
  103053. */
  103054. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  103055. var scene = this.getScene();
  103056. var defines = subMesh._materialDefines;
  103057. if (!defines) {
  103058. return;
  103059. }
  103060. var effect = subMesh.effect;
  103061. if (!effect) {
  103062. return;
  103063. }
  103064. this._activeEffect = effect;
  103065. // Matrices
  103066. this.bindOnlyWorldMatrix(world);
  103067. // Bones
  103068. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  103069. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  103070. if (mustRebind) {
  103071. this._uniformBuffer.bindToEffect(effect, "Material");
  103072. this.bindViewProjection(effect);
  103073. var reflectionTexture = this._reflectionTexture;
  103074. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  103075. // Texture uniforms
  103076. if (scene.texturesEnabled) {
  103077. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103078. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  103079. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  103080. }
  103081. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103082. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  103083. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  103084. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  103085. }
  103086. }
  103087. if (this.shadowLevel > 0) {
  103088. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  103089. }
  103090. this._uniformBuffer.updateFloat("alpha", this.alpha);
  103091. // Point size
  103092. if (this.pointsCloud) {
  103093. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  103094. }
  103095. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  103096. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  103097. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  103098. }
  103099. else {
  103100. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  103101. }
  103102. }
  103103. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  103104. // Textures
  103105. if (scene.texturesEnabled) {
  103106. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103107. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  103108. }
  103109. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103110. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  103111. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103112. }
  103113. else if (!defines.REFLECTIONBLUR) {
  103114. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103115. }
  103116. else {
  103117. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  103118. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  103119. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  103120. }
  103121. if (defines.REFLECTIONFRESNEL) {
  103122. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  103123. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  103124. }
  103125. }
  103126. }
  103127. // Clip plane
  103128. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  103129. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  103130. }
  103131. if (mustRebind || !this.isFrozen) {
  103132. if (scene.lightsEnabled) {
  103133. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  103134. }
  103135. // View
  103136. this.bindView(effect);
  103137. // Fog
  103138. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  103139. // image processing
  103140. if (this._imageProcessingConfiguration) {
  103141. this._imageProcessingConfiguration.bind(this._activeEffect);
  103142. }
  103143. }
  103144. this._uniformBuffer.update();
  103145. this._afterBind(mesh, this._activeEffect);
  103146. };
  103147. /**
  103148. * Dispose the material.
  103149. * @param forceDisposeEffect Force disposal of the associated effect.
  103150. * @param forceDisposeTextures Force disposal of the associated textures.
  103151. */
  103152. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  103153. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  103154. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  103155. if (forceDisposeTextures) {
  103156. if (this.diffuseTexture) {
  103157. this.diffuseTexture.dispose();
  103158. }
  103159. if (this.reflectionTexture) {
  103160. this.reflectionTexture.dispose();
  103161. }
  103162. }
  103163. this._renderTargets.dispose();
  103164. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103165. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103166. }
  103167. _super.prototype.dispose.call(this, forceDisposeEffect);
  103168. };
  103169. /**
  103170. * Clones the material.
  103171. * @param name The cloned name.
  103172. * @returns The cloned material.
  103173. */
  103174. BackgroundMaterial.prototype.clone = function (name) {
  103175. var _this = this;
  103176. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  103177. };
  103178. /**
  103179. * Serializes the current material to its JSON representation.
  103180. * @returns The JSON representation.
  103181. */
  103182. BackgroundMaterial.prototype.serialize = function () {
  103183. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103184. serializationObject.customType = "BABYLON.BackgroundMaterial";
  103185. return serializationObject;
  103186. };
  103187. /**
  103188. * Gets the class name of the material
  103189. * @returns "BackgroundMaterial"
  103190. */
  103191. BackgroundMaterial.prototype.getClassName = function () {
  103192. return "BackgroundMaterial";
  103193. };
  103194. /**
  103195. * Parse a JSON input to create back a background material.
  103196. * @param source The JSON data to parse
  103197. * @param scene The scene to create the parsed material in
  103198. * @param rootUrl The root url of the assets the material depends upon
  103199. * @returns the instantiated BackgroundMaterial.
  103200. */
  103201. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  103202. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  103203. };
  103204. /**
  103205. * Standard reflectance value at parallel view angle.
  103206. */
  103207. BackgroundMaterial.StandardReflectance0 = 0.05;
  103208. /**
  103209. * Standard reflectance value at grazing angle.
  103210. */
  103211. BackgroundMaterial.StandardReflectance90 = 0.5;
  103212. __decorate([
  103213. BABYLON.serializeAsColor3()
  103214. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  103215. __decorate([
  103216. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103217. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  103218. __decorate([
  103219. BABYLON.serializeAsColor3()
  103220. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  103221. __decorate([
  103222. BABYLON.serialize()
  103223. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  103224. __decorate([
  103225. BABYLON.serialize()
  103226. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  103227. __decorate([
  103228. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103229. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  103230. __decorate([
  103231. BABYLON.serializeAsTexture()
  103232. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  103233. __decorate([
  103234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103235. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  103236. __decorate([
  103237. BABYLON.serialize()
  103238. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  103239. __decorate([
  103240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103241. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  103242. __decorate([
  103243. BABYLON.serializeAsTexture()
  103244. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  103245. __decorate([
  103246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103247. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  103248. __decorate([
  103249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103250. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  103251. __decorate([
  103252. BABYLON.serialize()
  103253. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  103254. __decorate([
  103255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103256. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  103257. __decorate([
  103258. BABYLON.serializeAsVector3()
  103259. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  103260. __decorate([
  103261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103262. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  103263. __decorate([
  103264. BABYLON.serialize()
  103265. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  103266. __decorate([
  103267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103268. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  103269. __decorate([
  103270. BABYLON.serialize()
  103271. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  103272. __decorate([
  103273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103274. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  103275. __decorate([
  103276. BABYLON.serialize()
  103277. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  103278. __decorate([
  103279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103280. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  103281. __decorate([
  103282. BABYLON.serialize()
  103283. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  103284. __decorate([
  103285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103286. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  103287. __decorate([
  103288. BABYLON.serialize()
  103289. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  103290. __decorate([
  103291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103292. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  103293. __decorate([
  103294. BABYLON.serialize()
  103295. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  103296. __decorate([
  103297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103298. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  103299. __decorate([
  103300. BABYLON.serialize()
  103301. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  103302. __decorate([
  103303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103304. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  103305. __decorate([
  103306. BABYLON.serialize()
  103307. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  103308. __decorate([
  103309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103310. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  103311. __decorate([
  103312. BABYLON.serialize()
  103313. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  103314. __decorate([
  103315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103316. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  103317. __decorate([
  103318. BABYLON.serializeAsImageProcessingConfiguration()
  103319. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  103320. return BackgroundMaterial;
  103321. }(BABYLON.PushMaterial));
  103322. BABYLON.BackgroundMaterial = BackgroundMaterial;
  103323. })(BABYLON || (BABYLON = {}));
  103324. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  103325. var __assign = (this && this.__assign) || Object.assign || function(t) {
  103326. for (var s, i = 1, n = arguments.length; i < n; i++) {
  103327. s = arguments[i];
  103328. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  103329. t[p] = s[p];
  103330. }
  103331. return t;
  103332. };
  103333. var BABYLON;
  103334. (function (BABYLON) {
  103335. /**
  103336. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  103337. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  103338. * It also helps with the default setup of your imageProcessing configuration.
  103339. */
  103340. var EnvironmentHelper = /** @class */ (function () {
  103341. /**
  103342. * constructor
  103343. * @param options
  103344. * @param scene The scene to add the material to
  103345. */
  103346. function EnvironmentHelper(options, scene) {
  103347. var _this = this;
  103348. this._errorHandler = function (message, exception) {
  103349. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  103350. };
  103351. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  103352. this._scene = scene;
  103353. this.onErrorObservable = new BABYLON.Observable();
  103354. this._setupBackground();
  103355. this._setupImageProcessing();
  103356. }
  103357. /**
  103358. * Creates the default options for the helper.
  103359. */
  103360. EnvironmentHelper._getDefaultOptions = function () {
  103361. return {
  103362. createGround: true,
  103363. groundSize: 15,
  103364. groundTexture: this._groundTextureCDNUrl,
  103365. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103366. groundOpacity: 0.9,
  103367. enableGroundShadow: true,
  103368. groundShadowLevel: 0.5,
  103369. enableGroundMirror: false,
  103370. groundMirrorSizeRatio: 0.3,
  103371. groundMirrorBlurKernel: 64,
  103372. groundMirrorAmount: 1,
  103373. groundMirrorFresnelWeight: 1,
  103374. groundMirrorFallOffDistance: 0,
  103375. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  103376. groundYBias: 0.00001,
  103377. createSkybox: true,
  103378. skyboxSize: 20,
  103379. skyboxTexture: this._skyboxTextureCDNUrl,
  103380. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103381. backgroundYRotation: 0,
  103382. sizeAuto: true,
  103383. rootPosition: BABYLON.Vector3.Zero(),
  103384. setupImageProcessing: true,
  103385. environmentTexture: this._environmentTextureCDNUrl,
  103386. cameraExposure: 0.8,
  103387. cameraContrast: 1.2,
  103388. toneMappingEnabled: true,
  103389. };
  103390. };
  103391. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  103392. /**
  103393. * Gets the root mesh created by the helper.
  103394. */
  103395. get: function () {
  103396. return this._rootMesh;
  103397. },
  103398. enumerable: true,
  103399. configurable: true
  103400. });
  103401. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  103402. /**
  103403. * Gets the skybox created by the helper.
  103404. */
  103405. get: function () {
  103406. return this._skybox;
  103407. },
  103408. enumerable: true,
  103409. configurable: true
  103410. });
  103411. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  103412. /**
  103413. * Gets the skybox texture created by the helper.
  103414. */
  103415. get: function () {
  103416. return this._skyboxTexture;
  103417. },
  103418. enumerable: true,
  103419. configurable: true
  103420. });
  103421. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  103422. /**
  103423. * Gets the skybox material created by the helper.
  103424. */
  103425. get: function () {
  103426. return this._skyboxMaterial;
  103427. },
  103428. enumerable: true,
  103429. configurable: true
  103430. });
  103431. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  103432. /**
  103433. * Gets the ground mesh created by the helper.
  103434. */
  103435. get: function () {
  103436. return this._ground;
  103437. },
  103438. enumerable: true,
  103439. configurable: true
  103440. });
  103441. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  103442. /**
  103443. * Gets the ground texture created by the helper.
  103444. */
  103445. get: function () {
  103446. return this._groundTexture;
  103447. },
  103448. enumerable: true,
  103449. configurable: true
  103450. });
  103451. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  103452. /**
  103453. * Gets the ground mirror created by the helper.
  103454. */
  103455. get: function () {
  103456. return this._groundMirror;
  103457. },
  103458. enumerable: true,
  103459. configurable: true
  103460. });
  103461. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  103462. /**
  103463. * Gets the ground mirror render list to helps pushing the meshes
  103464. * you wish in the ground reflection.
  103465. */
  103466. get: function () {
  103467. if (this._groundMirror) {
  103468. return this._groundMirror.renderList;
  103469. }
  103470. return null;
  103471. },
  103472. enumerable: true,
  103473. configurable: true
  103474. });
  103475. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  103476. /**
  103477. * Gets the ground material created by the helper.
  103478. */
  103479. get: function () {
  103480. return this._groundMaterial;
  103481. },
  103482. enumerable: true,
  103483. configurable: true
  103484. });
  103485. /**
  103486. * Updates the background according to the new options
  103487. * @param options
  103488. */
  103489. EnvironmentHelper.prototype.updateOptions = function (options) {
  103490. var newOptions = __assign({}, this._options, options);
  103491. if (this._ground && !newOptions.createGround) {
  103492. this._ground.dispose();
  103493. this._ground = null;
  103494. }
  103495. if (this._groundMaterial && !newOptions.createGround) {
  103496. this._groundMaterial.dispose();
  103497. this._groundMaterial = null;
  103498. }
  103499. if (this._groundTexture) {
  103500. if (this._options.groundTexture != newOptions.groundTexture) {
  103501. this._groundTexture.dispose();
  103502. this._groundTexture = null;
  103503. }
  103504. }
  103505. if (this._skybox && !newOptions.createSkybox) {
  103506. this._skybox.dispose();
  103507. this._skybox = null;
  103508. }
  103509. if (this._skyboxMaterial && !newOptions.createSkybox) {
  103510. this._skyboxMaterial.dispose();
  103511. this._skyboxMaterial = null;
  103512. }
  103513. if (this._skyboxTexture) {
  103514. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  103515. this._skyboxTexture.dispose();
  103516. this._skyboxTexture = null;
  103517. }
  103518. }
  103519. if (this._groundMirror && !newOptions.enableGroundMirror) {
  103520. this._groundMirror.dispose();
  103521. this._groundMirror = null;
  103522. }
  103523. if (this._scene.environmentTexture) {
  103524. if (this._options.environmentTexture != newOptions.environmentTexture) {
  103525. this._scene.environmentTexture.dispose();
  103526. }
  103527. }
  103528. this._options = newOptions;
  103529. this._setupBackground();
  103530. this._setupImageProcessing();
  103531. };
  103532. /**
  103533. * Sets the primary color of all the available elements.
  103534. * @param color the main color to affect to the ground and the background
  103535. */
  103536. EnvironmentHelper.prototype.setMainColor = function (color) {
  103537. if (this.groundMaterial) {
  103538. this.groundMaterial.primaryColor = color;
  103539. }
  103540. if (this.skyboxMaterial) {
  103541. this.skyboxMaterial.primaryColor = color;
  103542. }
  103543. if (this.groundMirror) {
  103544. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  103545. }
  103546. };
  103547. /**
  103548. * Setup the image processing according to the specified options.
  103549. */
  103550. EnvironmentHelper.prototype._setupImageProcessing = function () {
  103551. if (this._options.setupImageProcessing) {
  103552. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  103553. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  103554. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  103555. this._setupEnvironmentTexture();
  103556. }
  103557. };
  103558. /**
  103559. * Setup the environment texture according to the specified options.
  103560. */
  103561. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  103562. if (this._scene.environmentTexture) {
  103563. return;
  103564. }
  103565. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  103566. this._scene.environmentTexture = this._options.environmentTexture;
  103567. return;
  103568. }
  103569. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  103570. this._scene.environmentTexture = environmentTexture;
  103571. };
  103572. /**
  103573. * Setup the background according to the specified options.
  103574. */
  103575. EnvironmentHelper.prototype._setupBackground = function () {
  103576. if (!this._rootMesh) {
  103577. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  103578. }
  103579. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  103580. var sceneSize = this._getSceneSize();
  103581. if (this._options.createGround) {
  103582. this._setupGround(sceneSize);
  103583. this._setupGroundMaterial();
  103584. this._setupGroundDiffuseTexture();
  103585. if (this._options.enableGroundMirror) {
  103586. this._setupGroundMirrorTexture(sceneSize);
  103587. }
  103588. this._setupMirrorInGroundMaterial();
  103589. }
  103590. if (this._options.createSkybox) {
  103591. this._setupSkybox(sceneSize);
  103592. this._setupSkyboxMaterial();
  103593. this._setupSkyboxReflectionTexture();
  103594. }
  103595. this._rootMesh.position.x = sceneSize.rootPosition.x;
  103596. this._rootMesh.position.z = sceneSize.rootPosition.z;
  103597. this._rootMesh.position.y = sceneSize.rootPosition.y;
  103598. };
  103599. /**
  103600. * Get the scene sizes according to the setup.
  103601. */
  103602. EnvironmentHelper.prototype._getSceneSize = function () {
  103603. var _this = this;
  103604. var groundSize = this._options.groundSize;
  103605. var skyboxSize = this._options.skyboxSize;
  103606. var rootPosition = this._options.rootPosition;
  103607. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  103608. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103609. }
  103610. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  103611. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  103612. });
  103613. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  103614. if (this._options.sizeAuto) {
  103615. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  103616. this._scene.activeCamera.upperRadiusLimit) {
  103617. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  103618. skyboxSize = groundSize;
  103619. }
  103620. var sceneDiagonalLenght = sceneDiagonal.length();
  103621. if (sceneDiagonalLenght > groundSize) {
  103622. groundSize = sceneDiagonalLenght * 2;
  103623. skyboxSize = groundSize;
  103624. }
  103625. // 10 % bigger.
  103626. groundSize *= 1.1;
  103627. skyboxSize *= 1.5;
  103628. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  103629. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  103630. }
  103631. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103632. };
  103633. /**
  103634. * Setup the ground according to the specified options.
  103635. */
  103636. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  103637. var _this = this;
  103638. if (!this._ground || this._ground.isDisposed()) {
  103639. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  103640. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  103641. this._ground.parent = this._rootMesh;
  103642. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  103643. }
  103644. this._ground.receiveShadows = this._options.enableGroundShadow;
  103645. };
  103646. /**
  103647. * Setup the ground material according to the specified options.
  103648. */
  103649. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  103650. if (!this._groundMaterial) {
  103651. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  103652. }
  103653. this._groundMaterial.alpha = this._options.groundOpacity;
  103654. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  103655. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  103656. this._groundMaterial.primaryColor = this._options.groundColor;
  103657. this._groundMaterial.useRGBColor = false;
  103658. this._groundMaterial.enableNoise = true;
  103659. if (this._ground) {
  103660. this._ground.material = this._groundMaterial;
  103661. }
  103662. };
  103663. /**
  103664. * Setup the ground diffuse texture according to the specified options.
  103665. */
  103666. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  103667. if (!this._groundMaterial) {
  103668. return;
  103669. }
  103670. if (this._groundTexture) {
  103671. return;
  103672. }
  103673. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  103674. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  103675. return;
  103676. }
  103677. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103678. diffuseTexture.gammaSpace = false;
  103679. diffuseTexture.hasAlpha = true;
  103680. this._groundMaterial.diffuseTexture = diffuseTexture;
  103681. };
  103682. /**
  103683. * Setup the ground mirror texture according to the specified options.
  103684. */
  103685. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  103686. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103687. if (!this._groundMirror) {
  103688. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  103689. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  103690. this._groundMirror.anisotropicFilteringLevel = 1;
  103691. this._groundMirror.wrapU = wrapping;
  103692. this._groundMirror.wrapV = wrapping;
  103693. this._groundMirror.gammaSpace = false;
  103694. if (this._groundMirror.renderList) {
  103695. for (var i = 0; i < this._scene.meshes.length; i++) {
  103696. var mesh = this._scene.meshes[i];
  103697. if (mesh !== this._ground &&
  103698. mesh !== this._skybox &&
  103699. mesh !== this._rootMesh) {
  103700. this._groundMirror.renderList.push(mesh);
  103701. }
  103702. }
  103703. }
  103704. }
  103705. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  103706. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  103707. };
  103708. /**
  103709. * Setup the ground to receive the mirror texture.
  103710. */
  103711. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  103712. if (this._groundMaterial) {
  103713. this._groundMaterial.reflectionTexture = this._groundMirror;
  103714. this._groundMaterial.reflectionFresnel = true;
  103715. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  103716. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  103717. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  103718. }
  103719. };
  103720. /**
  103721. * Setup the skybox according to the specified options.
  103722. */
  103723. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  103724. var _this = this;
  103725. if (!this._skybox || this._skybox.isDisposed()) {
  103726. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  103727. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  103728. }
  103729. this._skybox.parent = this._rootMesh;
  103730. };
  103731. /**
  103732. * Setup the skybox material according to the specified options.
  103733. */
  103734. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  103735. if (!this._skybox) {
  103736. return;
  103737. }
  103738. if (!this._skyboxMaterial) {
  103739. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  103740. }
  103741. this._skyboxMaterial.useRGBColor = false;
  103742. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  103743. this._skyboxMaterial.enableNoise = true;
  103744. this._skybox.material = this._skyboxMaterial;
  103745. };
  103746. /**
  103747. * Setup the skybox reflection texture according to the specified options.
  103748. */
  103749. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  103750. if (!this._skyboxMaterial) {
  103751. return;
  103752. }
  103753. if (this._skyboxTexture) {
  103754. return;
  103755. }
  103756. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  103757. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  103758. return;
  103759. }
  103760. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103761. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  103762. this._skyboxTexture.gammaSpace = false;
  103763. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  103764. };
  103765. /**
  103766. * Dispose all the elements created by the Helper.
  103767. */
  103768. EnvironmentHelper.prototype.dispose = function () {
  103769. if (this._groundMaterial) {
  103770. this._groundMaterial.dispose(true, true);
  103771. }
  103772. if (this._skyboxMaterial) {
  103773. this._skyboxMaterial.dispose(true, true);
  103774. }
  103775. this._rootMesh.dispose(false);
  103776. };
  103777. /**
  103778. * Default ground texture URL.
  103779. */
  103780. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  103781. /**
  103782. * Default skybox texture URL.
  103783. */
  103784. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  103785. /**
  103786. * Default environment texture URL.
  103787. */
  103788. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  103789. return EnvironmentHelper;
  103790. }());
  103791. BABYLON.EnvironmentHelper = EnvironmentHelper;
  103792. })(BABYLON || (BABYLON = {}));
  103793. //# sourceMappingURL=babylon.environmentHelper.js.map
  103794. var BABYLON;
  103795. (function (BABYLON) {
  103796. /** Internal class used to store shapes for emitters */
  103797. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  103798. function ParticleSystemSetEmitterCreationOptions() {
  103799. }
  103800. return ParticleSystemSetEmitterCreationOptions;
  103801. }());
  103802. /**
  103803. * Represents a set of particle systems working together to create a specific effect
  103804. */
  103805. var ParticleSystemSet = /** @class */ (function () {
  103806. function ParticleSystemSet() {
  103807. /**
  103808. * Gets the particle system list
  103809. */
  103810. this.systems = new Array();
  103811. }
  103812. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  103813. /**
  103814. * Gets the emitter node used with this set
  103815. */
  103816. get: function () {
  103817. return this._emitterNode;
  103818. },
  103819. enumerable: true,
  103820. configurable: true
  103821. });
  103822. /**
  103823. * Creates a new emitter mesh as a sphere
  103824. * @param options defines the options used to create the sphere
  103825. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  103826. * @param scene defines the hosting scene
  103827. */
  103828. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103829. if (this._emitterNode) {
  103830. this._emitterNode.dispose();
  103831. }
  103832. this._emitterCreationOptions = {
  103833. kind: "Sphere",
  103834. options: options,
  103835. renderingGroupId: renderingGroupId
  103836. };
  103837. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103838. emitterMesh.renderingGroupId = renderingGroupId;
  103839. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103840. material.emissiveColor = options.color;
  103841. emitterMesh.material = material;
  103842. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103843. var system = _a[_i];
  103844. system.emitter = emitterMesh;
  103845. }
  103846. this._emitterNode = emitterMesh;
  103847. };
  103848. /**
  103849. * Starts all particle systems of the set
  103850. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103851. */
  103852. ParticleSystemSet.prototype.start = function (emitter) {
  103853. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103854. var system = _a[_i];
  103855. if (emitter) {
  103856. system.emitter = emitter;
  103857. }
  103858. system.start();
  103859. }
  103860. };
  103861. /**
  103862. * Release all associated resources
  103863. */
  103864. ParticleSystemSet.prototype.dispose = function () {
  103865. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103866. var system = _a[_i];
  103867. system.dispose();
  103868. }
  103869. this.systems = [];
  103870. if (this._emitterNode) {
  103871. this._emitterNode.dispose();
  103872. this._emitterNode = null;
  103873. }
  103874. };
  103875. /**
  103876. * Serialize the set into a JSON compatible object
  103877. * @returns a JSON compatible representation of the set
  103878. */
  103879. ParticleSystemSet.prototype.serialize = function () {
  103880. var result = {};
  103881. result.systems = [];
  103882. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103883. var system = _a[_i];
  103884. result.systems.push(system.serialize());
  103885. }
  103886. if (this._emitterNode) {
  103887. result.emitter = this._emitterCreationOptions;
  103888. }
  103889. return result;
  103890. };
  103891. /**
  103892. * Parse a new ParticleSystemSet from a serialized source
  103893. * @param data defines a JSON compatible representation of the set
  103894. * @param scene defines the hosting scene
  103895. * @param gpu defines if we want GPU particles or CPU particles
  103896. * @returns a new ParticleSystemSet
  103897. */
  103898. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103899. if (gpu === void 0) { gpu = false; }
  103900. var result = new ParticleSystemSet();
  103901. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103902. scene = scene || BABYLON.Engine.LastCreatedScene;
  103903. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103904. var system = _a[_i];
  103905. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103906. }
  103907. if (data.emitter) {
  103908. var options = data.emitter.options;
  103909. switch (data.emitter.kind) {
  103910. case "Sphere":
  103911. result.setEmitterAsSphere({
  103912. diameter: options.diameter,
  103913. segments: options.segments,
  103914. color: BABYLON.Color3.FromArray(options.color)
  103915. }, data.emitter.renderingGroupId, scene);
  103916. break;
  103917. }
  103918. }
  103919. return result;
  103920. };
  103921. return ParticleSystemSet;
  103922. }());
  103923. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103924. })(BABYLON || (BABYLON = {}));
  103925. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103926. var BABYLON;
  103927. (function (BABYLON) {
  103928. /**
  103929. * This class is made for on one-liner static method to help creating particle system set.
  103930. */
  103931. var ParticleHelper = /** @class */ (function () {
  103932. function ParticleHelper() {
  103933. }
  103934. /**
  103935. * This is the main static method (one-liner) of this helper to create different particle systems
  103936. * @param type This string represents the type to the particle system to create
  103937. * @param scene The scene where the particle system should live
  103938. * @param gpu If the system will use gpu
  103939. * @returns the ParticleSystemSet created
  103940. */
  103941. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103942. if (gpu === void 0) { gpu = false; }
  103943. if (!scene) {
  103944. scene = BABYLON.Engine.LastCreatedScene;
  103945. ;
  103946. }
  103947. var token = {};
  103948. scene._addPendingData(token);
  103949. return new Promise(function (resolve, reject) {
  103950. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103951. scene._removePendingData(token);
  103952. return reject("Particle system with GPU is not supported.");
  103953. }
  103954. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103955. scene._removePendingData(token);
  103956. var newData = JSON.parse(data.toString());
  103957. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103958. }, undefined, undefined, undefined, function (req, exception) {
  103959. scene._removePendingData(token);
  103960. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103961. });
  103962. });
  103963. };
  103964. /**
  103965. * Static function used to export a particle system to a ParticleSystemSet variable.
  103966. * Please note that the emitter shape is not exported
  103967. * @param system defines the particle systems to export
  103968. */
  103969. ParticleHelper.ExportSet = function (systems) {
  103970. var set = new BABYLON.ParticleSystemSet();
  103971. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103972. var system = systems_1[_i];
  103973. set.systems.push(system);
  103974. }
  103975. return set;
  103976. };
  103977. /**
  103978. * Gets or sets base Assets URL
  103979. */
  103980. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103981. return ParticleHelper;
  103982. }());
  103983. BABYLON.ParticleHelper = ParticleHelper;
  103984. })(BABYLON || (BABYLON = {}));
  103985. //# sourceMappingURL=babylon.particleHelper.js.map
  103986. var BABYLON;
  103987. (function (BABYLON) {
  103988. /**
  103989. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103990. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103991. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103992. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103993. */
  103994. var VideoDome = /** @class */ (function (_super) {
  103995. __extends(VideoDome, _super);
  103996. /**
  103997. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103998. * @param name Element's name, child elements will append suffixes for their own names.
  103999. * @param urlsOrVideo defines the url(s) or the video element to use
  104000. * @param options An object containing optional or exposed sub element properties
  104001. */
  104002. function VideoDome(name, urlsOrVideo, options, scene) {
  104003. var _this = _super.call(this, name, scene) || this;
  104004. _this._useDirectMapping = false;
  104005. // set defaults and manage values
  104006. name = name || "videoDome";
  104007. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104008. options.clickToPlay = Boolean(options.clickToPlay);
  104009. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  104010. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  104011. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104012. if (options.useDirectMapping === undefined) {
  104013. _this._useDirectMapping = true;
  104014. }
  104015. else {
  104016. _this._useDirectMapping = options.useDirectMapping;
  104017. }
  104018. _this._setReady(false);
  104019. // create
  104020. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  104021. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104022. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  104023. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104024. texture.onLoadObservable.addOnce(function () {
  104025. _this._setReady(true);
  104026. });
  104027. // configure material
  104028. material.useEquirectangularFOV = true;
  104029. material.fovMultiplier = 1.0;
  104030. material.opacityFresnel = false;
  104031. if (_this._useDirectMapping) {
  104032. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104033. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104034. material.diffuseTexture = texture;
  104035. }
  104036. else {
  104037. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104038. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104039. material.reflectionTexture = texture;
  104040. }
  104041. // configure mesh
  104042. _this._mesh.material = material;
  104043. _this._mesh.parent = _this;
  104044. // optional configuration
  104045. if (options.clickToPlay) {
  104046. scene.onPointerUp = function () {
  104047. _this._videoTexture.video.play();
  104048. };
  104049. }
  104050. return _this;
  104051. }
  104052. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  104053. /**
  104054. * Gets the video texture being displayed on the sphere
  104055. */
  104056. get: function () {
  104057. return this._videoTexture;
  104058. },
  104059. enumerable: true,
  104060. configurable: true
  104061. });
  104062. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  104063. /**
  104064. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104065. * Also see the options.resolution property.
  104066. */
  104067. get: function () {
  104068. return this._material.fovMultiplier;
  104069. },
  104070. set: function (value) {
  104071. this._material.fovMultiplier = value;
  104072. },
  104073. enumerable: true,
  104074. configurable: true
  104075. });
  104076. /**
  104077. * Releases resources associated with this node.
  104078. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104079. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104080. */
  104081. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104082. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104083. this._videoTexture.dispose();
  104084. this._mesh.dispose();
  104085. this._material.dispose();
  104086. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104087. };
  104088. return VideoDome;
  104089. }(BABYLON.Node));
  104090. BABYLON.VideoDome = VideoDome;
  104091. })(BABYLON || (BABYLON = {}));
  104092. //# sourceMappingURL=babylon.videoDome.js.map
  104093. var BABYLON;
  104094. (function (BABYLON) {
  104095. /**
  104096. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  104097. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  104098. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  104099. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104100. */
  104101. var PhotoDome = /** @class */ (function (_super) {
  104102. __extends(PhotoDome, _super);
  104103. /**
  104104. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  104105. * @param name Element's name, child elements will append suffixes for their own names.
  104106. * @param urlsOfPhoto define the url of the photo to display
  104107. * @param options An object containing optional or exposed sub element properties
  104108. */
  104109. function PhotoDome(name, urlOfPhoto, options, scene) {
  104110. var _this = _super.call(this, name, scene) || this;
  104111. _this._useDirectMapping = false;
  104112. // set defaults and manage values
  104113. name = name || "photoDome";
  104114. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104115. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104116. if (options.useDirectMapping === undefined) {
  104117. _this._useDirectMapping = true;
  104118. }
  104119. else {
  104120. _this._useDirectMapping = options.useDirectMapping;
  104121. }
  104122. _this._setReady(false);
  104123. // create
  104124. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104125. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104126. // configure material
  104127. material.opacityFresnel = false;
  104128. material.useEquirectangularFOV = true;
  104129. material.fovMultiplier = 1.0;
  104130. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  104131. _this.photoTexture.onLoadObservable.addOnce(function () {
  104132. _this._setReady(true);
  104133. });
  104134. // configure mesh
  104135. _this._mesh.material = material;
  104136. _this._mesh.parent = _this;
  104137. return _this;
  104138. }
  104139. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  104140. /**
  104141. * Gets or sets the texture being displayed on the sphere
  104142. */
  104143. get: function () {
  104144. return this._photoTexture;
  104145. },
  104146. set: function (value) {
  104147. if (this._photoTexture === value) {
  104148. return;
  104149. }
  104150. this._photoTexture = value;
  104151. if (this._useDirectMapping) {
  104152. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104153. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104154. this._material.diffuseTexture = this._photoTexture;
  104155. }
  104156. else {
  104157. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104158. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104159. this._material.reflectionTexture = this._photoTexture;
  104160. }
  104161. },
  104162. enumerable: true,
  104163. configurable: true
  104164. });
  104165. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  104166. /**
  104167. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104168. * Also see the options.resolution property.
  104169. */
  104170. get: function () {
  104171. return this._material.fovMultiplier;
  104172. },
  104173. set: function (value) {
  104174. this._material.fovMultiplier = value;
  104175. },
  104176. enumerable: true,
  104177. configurable: true
  104178. });
  104179. /**
  104180. * Releases resources associated with this node.
  104181. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104182. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104183. */
  104184. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104185. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104186. this._photoTexture.dispose();
  104187. this._mesh.dispose();
  104188. this._material.dispose();
  104189. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104190. };
  104191. return PhotoDome;
  104192. }(BABYLON.Node));
  104193. BABYLON.PhotoDome = PhotoDome;
  104194. })(BABYLON || (BABYLON = {}));
  104195. //# sourceMappingURL=babylon.photoDome.js.map
  104196. var BABYLON;
  104197. (function (BABYLON) {
  104198. BABYLON.Engine.prototype.createQuery = function () {
  104199. return this._gl.createQuery();
  104200. };
  104201. BABYLON.Engine.prototype.deleteQuery = function (query) {
  104202. this._gl.deleteQuery(query);
  104203. return this;
  104204. };
  104205. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  104206. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  104207. };
  104208. BABYLON.Engine.prototype.getQueryResult = function (query) {
  104209. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  104210. };
  104211. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  104212. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104213. this._gl.beginQuery(glAlgorithm, query);
  104214. return this;
  104215. };
  104216. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  104217. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104218. this._gl.endQuery(glAlgorithm);
  104219. return this;
  104220. };
  104221. BABYLON.Engine.prototype._createTimeQuery = function () {
  104222. var timerQuery = this.getCaps().timerQuery;
  104223. if (timerQuery.createQueryEXT) {
  104224. return timerQuery.createQueryEXT();
  104225. }
  104226. return this.createQuery();
  104227. };
  104228. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  104229. var timerQuery = this.getCaps().timerQuery;
  104230. if (timerQuery.deleteQueryEXT) {
  104231. timerQuery.deleteQueryEXT(query);
  104232. return;
  104233. }
  104234. this.deleteQuery(query);
  104235. };
  104236. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  104237. var timerQuery = this.getCaps().timerQuery;
  104238. if (timerQuery.getQueryObjectEXT) {
  104239. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  104240. }
  104241. return this.getQueryResult(query);
  104242. };
  104243. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  104244. var timerQuery = this.getCaps().timerQuery;
  104245. if (timerQuery.getQueryObjectEXT) {
  104246. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  104247. }
  104248. return this.isQueryResultAvailable(query);
  104249. };
  104250. BABYLON.Engine.prototype.startTimeQuery = function () {
  104251. var caps = this.getCaps();
  104252. var timerQuery = caps.timerQuery;
  104253. if (!timerQuery) {
  104254. return null;
  104255. }
  104256. var token = new BABYLON._TimeToken();
  104257. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104258. if (caps.canUseTimestampForTimerQuery) {
  104259. token._startTimeQuery = this._createTimeQuery();
  104260. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  104261. }
  104262. else {
  104263. if (this._currentNonTimestampToken) {
  104264. return this._currentNonTimestampToken;
  104265. }
  104266. token._timeElapsedQuery = this._createTimeQuery();
  104267. if (timerQuery.beginQueryEXT) {
  104268. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104269. }
  104270. else {
  104271. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104272. }
  104273. this._currentNonTimestampToken = token;
  104274. }
  104275. return token;
  104276. };
  104277. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  104278. var caps = this.getCaps();
  104279. var timerQuery = caps.timerQuery;
  104280. if (!timerQuery || !token) {
  104281. return -1;
  104282. }
  104283. if (caps.canUseTimestampForTimerQuery) {
  104284. if (!token._startTimeQuery) {
  104285. return -1;
  104286. }
  104287. if (!token._endTimeQuery) {
  104288. token._endTimeQuery = this._createTimeQuery();
  104289. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  104290. }
  104291. }
  104292. else if (!token._timeElapsedQueryEnded) {
  104293. if (!token._timeElapsedQuery) {
  104294. return -1;
  104295. }
  104296. if (timerQuery.endQueryEXT) {
  104297. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  104298. }
  104299. else {
  104300. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  104301. }
  104302. token._timeElapsedQueryEnded = true;
  104303. }
  104304. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104305. var available = false;
  104306. if (token._endTimeQuery) {
  104307. available = this._getTimeQueryAvailability(token._endTimeQuery);
  104308. }
  104309. else if (token._timeElapsedQuery) {
  104310. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  104311. }
  104312. if (available && !disjoint) {
  104313. var result = 0;
  104314. if (caps.canUseTimestampForTimerQuery) {
  104315. if (!token._startTimeQuery || !token._endTimeQuery) {
  104316. return -1;
  104317. }
  104318. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  104319. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  104320. result = timeEnd - timeStart;
  104321. this._deleteTimeQuery(token._startTimeQuery);
  104322. this._deleteTimeQuery(token._endTimeQuery);
  104323. token._startTimeQuery = null;
  104324. token._endTimeQuery = null;
  104325. }
  104326. else {
  104327. if (!token._timeElapsedQuery) {
  104328. return -1;
  104329. }
  104330. result = this._getTimeQueryResult(token._timeElapsedQuery);
  104331. this._deleteTimeQuery(token._timeElapsedQuery);
  104332. token._timeElapsedQuery = null;
  104333. token._timeElapsedQueryEnded = false;
  104334. this._currentNonTimestampToken = null;
  104335. }
  104336. return result;
  104337. }
  104338. return -1;
  104339. };
  104340. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  104341. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  104342. };
  104343. // We also need to update AbstractMesh as there is a portion of the code there
  104344. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  104345. var engine = this.getEngine();
  104346. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  104347. this._isOccluded = false;
  104348. return;
  104349. }
  104350. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  104351. this._isOccluded = false;
  104352. return;
  104353. }
  104354. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  104355. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  104356. if (isOcclusionQueryAvailable) {
  104357. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  104358. this._isOcclusionQueryInProgress = false;
  104359. this._occlusionInternalRetryCounter = 0;
  104360. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  104361. }
  104362. else {
  104363. this._occlusionInternalRetryCounter++;
  104364. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  104365. this._isOcclusionQueryInProgress = false;
  104366. this._occlusionInternalRetryCounter = 0;
  104367. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  104368. // if strict continue the last state of the object.
  104369. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  104370. }
  104371. else {
  104372. return;
  104373. }
  104374. }
  104375. }
  104376. var scene = this.getScene();
  104377. if (scene.getBoundingBoxRenderer) {
  104378. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  104379. if (!this._occlusionQuery) {
  104380. this._occlusionQuery = engine.createQuery();
  104381. }
  104382. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  104383. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  104384. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  104385. this._isOcclusionQueryInProgress = true;
  104386. }
  104387. };
  104388. })(BABYLON || (BABYLON = {}));
  104389. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  104390. var BABYLON;
  104391. (function (BABYLON) {
  104392. /**
  104393. * Class used to generate noise procedural textures
  104394. */
  104395. var NoiseProceduralTexture = /** @class */ (function (_super) {
  104396. __extends(NoiseProceduralTexture, _super);
  104397. /**
  104398. * Creates a new NoiseProceduralTexture
  104399. * @param name defines the name fo the texture
  104400. * @param size defines the size of the texture (default is 256)
  104401. * @param scene defines the hosting scene
  104402. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  104403. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  104404. */
  104405. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  104406. if (size === void 0) { size = 256; }
  104407. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  104408. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  104409. _this._time = 0;
  104410. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  104411. _this.brightness = 0.2;
  104412. /** Defines the number of octaves to process */
  104413. _this.octaves = 3;
  104414. /** Defines the level of persistence (0.8 by default) */
  104415. _this.persistence = 0.8;
  104416. /** Gets or sets animation speed factor (default is 1) */
  104417. _this.animationSpeedFactor = 1;
  104418. _this._updateShaderUniforms();
  104419. return _this;
  104420. }
  104421. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  104422. var scene = this.getScene();
  104423. if (!scene) {
  104424. return;
  104425. }
  104426. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  104427. this.setFloat("brightness", this.brightness);
  104428. this.setInt("octaves", this.octaves);
  104429. this.setFloat("persistence", this.persistence);
  104430. this.setFloat("timeScale", this._time);
  104431. };
  104432. /** Generate the current state of the procedural texture */
  104433. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  104434. this._updateShaderUniforms();
  104435. _super.prototype.render.call(this, useCameraPostProcess);
  104436. };
  104437. /**
  104438. * Serializes this noise procedural texture
  104439. * @returns a serialized noise procedural texture object
  104440. */
  104441. NoiseProceduralTexture.prototype.serialize = function () {
  104442. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  104443. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  104444. return serializationObject;
  104445. };
  104446. /**
  104447. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  104448. * @param parsedTexture defines parsed texture data
  104449. * @param scene defines the current scene
  104450. * @param rootUrl defines the root URL containing noise procedural texture information
  104451. * @returns a parsed NoiseProceduralTexture
  104452. */
  104453. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  104454. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  104455. return texture;
  104456. };
  104457. return NoiseProceduralTexture;
  104458. }(BABYLON.ProceduralTexture));
  104459. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  104460. })(BABYLON || (BABYLON = {}));
  104461. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  104462. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<octaves; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  104463. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};